Rhai is an embedded scripting language for Rust. It is meant to be a safe drop-in for your own projects and doesn't use any additional dependencies, unsafe code, or APIs outside of the ones you provide in your program. This allows you to have rich control over the functionality exposed to the scripting context.
Rhai's scripting engine is very lightweight. It gets its ability from the functions in your program. To call these functions, you need to register them with the scripting engine.
```Rust
fn add(x: i32, y: i32) -> i32 {
x + y
}
fn main() {
let mut engine = Engine::new();
&(add as fn(x: i32, y: i32)->i32).register(&mut engine, "add");
if let Ok(result) = engine.eval("add(40, 2)".to_string()).unwrap().downcast::<i32>() {
To use methods and functions with the engine, we need to register them. There are some convenience functions to help with this. Below I register update and new with the engine.
&(TestStruct::update as fn(&mut TestStruct)->()).register(&mut engine, "update");
&(TestStruct::new as fn()->TestStruct).register(&mut engine, "new_ts");
```
Finally, we call our script. The script can see the function and method we registered earlier. We need to get the result back out from script land just as before, this time casting to our custom struct type.