From 78794d7dfc87a989abdcd2b5b0e05d48045e8a12 Mon Sep 17 00:00:00 2001 From: Stephen Chung Date: Sat, 12 Feb 2022 12:41:10 +0800 Subject: [PATCH] Add callback example. --- examples/callback.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 examples/callback.rs diff --git a/examples/callback.rs b/examples/callback.rs new file mode 100644 index 00000000..40791bcd --- /dev/null +++ b/examples/callback.rs @@ -0,0 +1,34 @@ +//! This example stores a Rhai closure for later use as a callback. + +use rhai::{Engine, EvalAltResult, FnPtr}; + +fn main() -> Result<(), Box> { + // This script creates a closure which may capture variables. + let script = " + let x = 20; + + // The following closure captures 'x' + return |a, b| (x + a) * b; + "; + + // 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`). + let engine = Engine::new(); + + let ast = engine.compile(script)?; + + let closure = engine.eval_ast::(&ast)?; + + // Create a closure that we can call any time, encapsulating the + // `Engine`, `AST` and `FnPtr`. + let func = move |x: i64, y: i64| -> Result { closure.call(&engine, &ast, (x, y)) }; + + // Now we can call `func` anywhere just like a normal function! + let result = func(1, 2)?; + + println!("The Answer: {}", result); // prints 42 + + Ok(()) +}