rhai/examples/callback.rs

43 lines
1.3 KiB
Rust
Raw Normal View History

2022-02-12 05:41:10 +01:00
//! This example stores a Rhai closure for later use as a callback.
use rhai::{Engine, EvalAltResult, FnPtr};
2022-02-16 02:12:34 +01:00
// To call a Rhai closure at a later time, you'd need three things:
// 1) an `Engine` (with all needed functions registered),
// 2) a compiled `AST`,
// 3) the closure (of type `FnPtr`).
2022-02-12 05:41:10 +01:00
fn main() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
2022-02-16 02:12:34 +01:00
// This script creates a closure which captures a variable and returns it.
let ast = engine.compile(
"
let x = 18;
// The following closure captures 'x'
return |a, b| {
x += 1; // x is incremented each time
(x + a) * b
};
",
)?;
2022-02-12 05:41:10 +01:00
let closure = engine.eval_ast::<FnPtr>(&ast)?;
2022-02-16 02:12:34 +01:00
// Create a closure by encapsulating the `Engine`, `AST` and `FnPtr`.
// In a real application, you'd be handling errors.
let func = move |x: i64, y: i64| -> i64 { closure.call(&engine, &ast, (x, y)).unwrap() };
2022-02-12 05:41:10 +01:00
// Now we can call `func` anywhere just like a normal function!
2022-02-16 02:12:34 +01:00
let r1 = func(1, 2);
// Notice that each call to `func` returns a different value
// because the captured `x` is always changing!
let r2 = func(1, 2);
let r3 = func(1, 2);
2022-02-12 05:41:10 +01:00
println!("The Answers: {r1}, {r2}, {r3}"); // prints 40, 42, 44
2022-02-12 05:41:10 +01:00
Ok(())
}