Overloadable index operation

This commit is contained in:
Robert Bendun 2022-05-24 16:38:18 +02:00
parent 15f5e66e0b
commit d549d23f0a
3 changed files with 15 additions and 2 deletions

View File

@ -137,9 +137,8 @@ Interpreter::Interpreter()
operators["."] = +[](Interpreter &i, std::vector<Value> args) -> Result<Value> {
assert(args.size() == 2, "Operator . requires two arguments"); // TODO(assert)
assert(args.front().type == Value::Type::Block, "Only blocks can be indexed"); // TODO(assert)
assert(args.back().type == Value::Type::Number, "Only numbers can be used for indexing"); // TODO(assert)
return std::move(args.front()).blk.index(i, std::move(args.back()).n.as_int());
return std::move(args.front()).index(i, std::move(args.back()).n.as_int());
};
}
}

View File

@ -525,6 +525,7 @@ struct Value
bool truthy() const;
bool falsy() const;
Result<Value> operator()(Interpreter &i, std::vector<Value> args);
Result<Value> index(Interpreter &i, unsigned position);
bool operator==(Value const& other) const;
};

View File

@ -155,6 +155,19 @@ Result<Value> Value::operator()(Interpreter &i, std::vector<Value> args)
}
}
Result<Value> Value::index(Interpreter &i, unsigned position)
{
switch (type) {
case Type::Block:
return blk.index(i, position);
default:
assert(false, "Block indexing is not supported for this type"); // TODO(assert)
}
unreachable();
}
bool Value::truthy() const
{
switch (type) {