rhaiscript / rhai

Rhai - An embedded scripting language for Rust.
https://crates.io/crates/rhai
Apache License 2.0
3.77k stars 178 forks source link

How to use global variable in rhai function declared in rust #922

Open rawhuul opened 17 hours ago

rawhuul commented 17 hours ago

Hi, there I want to call a function foo which will update the scope variable named bar but it must be implemented in Rust.

fn foo(scope: &mut Scope, path: &str) {
    scope.set_or_push("bar", path);
}

But upon calling the function as:

foo("abcd")

it throws error:

Error: ErrorFunctionNotFound("foo (&str | ImmutableString | String)", 2:9)

Can I pass the scope as argument (which is not an ideal choice), is there any workaround to that?

schungx commented 11 hours ago

You cannot. You cannot modify the scope within a Rust function.

Rhai depends on you not being able to modify the scope for some of its optimizations.