Merge branch 'master' into plugins
This commit is contained in:
@@ -200,7 +200,7 @@ type MyType = Rc<RefCell<INT>>;
|
||||
#[test]
|
||||
#[cfg(not(feature = "no_object"))]
|
||||
#[cfg(not(feature = "sync"))]
|
||||
fn test_closure_shared_obj() -> Result<(), Box<EvalAltResult>> {
|
||||
fn test_closures_shared_obj() -> Result<(), Box<EvalAltResult>> {
|
||||
let mut engine = Engine::new();
|
||||
|
||||
// Register API on MyType
|
||||
@@ -250,3 +250,30 @@ fn test_closure_shared_obj() -> Result<(), Box<EvalAltResult>> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(feature = "no_closure"))]
|
||||
fn test_closures_external() -> Result<(), Box<EvalAltResult>> {
|
||||
let engine = Engine::new();
|
||||
|
||||
let mut ast = engine.compile(
|
||||
r#"
|
||||
let test = "hello";
|
||||
|
||||
|x| test + x
|
||||
"#,
|
||||
)?;
|
||||
|
||||
// Save the function pointer together with captured variables
|
||||
let fn_ptr = engine.eval_ast::<FnPtr>(&ast)?;
|
||||
|
||||
// Get rid of the script, retaining only functions
|
||||
ast.retain_functions(|_, _, _| true);
|
||||
|
||||
// Closure 'f' captures: the engine, the AST, and the curried function pointer
|
||||
let f = move |x: INT| fn_ptr.call_dynamic(&engine, ast, None, [x.into()]);
|
||||
|
||||
assert_eq!(f(42)?.as_str(), Ok("hello42"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
33
tests/packages.rs
Normal file
33
tests/packages.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use rhai::{Engine, EvalAltResult, INT, Scope};
|
||||
use rhai::packages::{Package, StandardPackage};
|
||||
|
||||
#[test]
|
||||
fn test_packages() -> Result<(), Box<EvalAltResult>> {
|
||||
let e = Engine::new();
|
||||
let ast = e.compile("x")?;
|
||||
let std_pkg = StandardPackage::new();
|
||||
|
||||
let make_call = |x: INT| -> Result<INT, Box<EvalAltResult>> {
|
||||
// Create a raw Engine - extremely cheap.
|
||||
let mut engine = Engine::new_raw();
|
||||
|
||||
// Load packages - cheap.
|
||||
engine.load_package(std_pkg.get());
|
||||
|
||||
// Create custom scope - cheap.
|
||||
let mut scope = Scope::new();
|
||||
|
||||
// Push variable into scope - relatively cheap.
|
||||
scope.push("x", x);
|
||||
|
||||
// Evaluate script.
|
||||
engine.eval_ast_with_scope::<INT>(&mut scope, &ast)
|
||||
};
|
||||
|
||||
// The following loop creates 10,000 Engine instances!
|
||||
for x in 0..10_000 {
|
||||
assert_eq!(make_call(x)?, x);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
Reference in New Issue
Block a user