rhaiscript / rhai

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

Passing data to a script as a variable #221

Closed bheylin closed 4 years ago

bheylin commented 4 years ago

I have a struct I want to pass to a script. Atm I'm calling a get_input_data() function from the script and binding the struct to a var. This works fine, but means all scripts have to have the first line.

I would like to just set this data to a var called input. From what I can see, that is maybe possible by getting the root package (CorePackage?) and reaching into the module, where I could call set_var.

let core_package = CorePackage::new(); let core_module = core_package.get(); // core_module needs to be mutable, but it's wrapped in an Rc<> core_module.set_var("test_input", "test_string"); engine.load_package(core_module);

But I can't access the set_var function dues to mutability constraints.

So firstly, Is it possible to set a variable from Rust for use by a Rhai script? second, if so, am I going about this the right way?

Thanks ;)

schungx commented 4 years ago

Just pass it inside a scope:

let payload = SomeThingIWantToPassToAScript::new();

let mut scope = Scope::new();

scope.push_constant("master_input", payload);

engine.eval_with_scope(&mut scope, script)?;
bheylin commented 4 years ago

@schungx excellent, works like a charm ;)