ADD: ref! to mutate array elements.

main
bog 2023-09-24 15:54:57 +02:00
parent f9f73dabd3
commit 9a8f4096ea
7 changed files with 35 additions and 2 deletions

View File

@ -17,4 +17,14 @@
(assert= 4 (second (produce)))
($ arr [2 'bim' produce false])
(assert= 6 (ref ((ref arr 2)) 2))
(assert= 6 (ref ((ref arr 2)) 2))
($ hello [2 4 6])
(assert= 4 (ref hello 1))
(ref! hello 1 12)
(assert= 12 (ref hello 1))
($ hello2 [[5 7][9 2]])
(assert= 9 (ref hello2 1 0))
(ref! (ref hello2 1) 0 34)
(assert= 34 (ref hello2 1 0))

View File

@ -339,6 +339,20 @@ namespace fkstd
return val->at(std::get<int>(args.back()->value()));
}
STDRET array_set(Loc, Module& mod, STDARGS args)
{
auto ref_val = args[0]->value();
size_t ref = std::get<size_t>(ref_val);
int index = std::get<int>(args[1]->value());
std::shared_ptr<Array> val =
std::get<std::shared_ptr<Array>>(mod.vm()->load_global(ref));
val->set(index, args[2]);
return args[2];
}
STDRET string_cat(Loc loc, Module&, STDARGS args)
{
if (args.empty())

View File

@ -30,6 +30,7 @@ namespace fkstd
STDRET bool_not(Loc loc, Module& mod, STDARGS args);
STDRET array_ref(Loc loc, Module& mod, STDARGS args);
STDRET array_set(Loc loc, Module& mod, STDARGS args);
STDRET string_cat(Loc loc, Module& mod, STDARGS args);
STDRET string_dup(Loc loc, Module& mod, STDARGS args);

View File

@ -29,6 +29,7 @@ extern "C" void lib(Module& mod)
mod.register_function("not", fkstd::bool_not);
mod.register_function("ref", fkstd::array_ref);
mod.register_function("ref!", fkstd::array_set);
mod.register_function("cat", fkstd::string_cat);
mod.register_function("dup", fkstd::string_dup);
mod.register_function("char-at", fkstd::char_at);

View File

@ -9,7 +9,7 @@ namespace fkstd
{
auto ident = node->child(1)->repr();
compiler.compile_prog(node->child(2), program);
std::cout << "push " << node->child(2)->string() << std::endl;
auto entry = compiler.sym()->find(ident);
if (entry)

View File

@ -22,6 +22,12 @@ namespace fk
return m_data.at(index);
}
void Array::set(size_t index, std::shared_ptr<Constant> value)
{
assert(index < size());
m_data[index] = value;
}
std::shared_ptr<Constant> Array::pop()
{
assert(size() > 0);

View File

@ -17,6 +17,7 @@ namespace fk
void push(std::shared_ptr<Constant> constant);
std::shared_ptr<Constant> at(size_t index) const;
void set(size_t index, std::shared_ptr<Constant> value);
std::shared_ptr<Constant> pop();
std::string string() const;