2020-08-23 11:22:39 +02:00
|
|
|
use rhai::packages::{Package, StandardPackage};
|
2020-09-11 16:32:59 +02:00
|
|
|
use rhai::{Engine, EvalAltResult, Module, Scope, INT};
|
2020-08-23 11:22:39 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_packages() -> Result<(), Box<EvalAltResult>> {
|
2020-09-11 16:32:59 +02:00
|
|
|
let engine = Engine::new();
|
|
|
|
let ast = engine.compile("x")?;
|
2020-08-23 11:22:39 +02:00
|
|
|
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)
|
|
|
|
};
|
|
|
|
|
2020-09-11 16:32:59 +02:00
|
|
|
assert_eq!(make_call(42)?, 42);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2020-09-11 16:56:19 +02:00
|
|
|
#[cfg(not(feature = "no_function"))]
|
|
|
|
#[cfg(not(feature = "no_module"))]
|
2020-09-11 16:32:59 +02:00
|
|
|
#[test]
|
|
|
|
fn test_packages_with_script() -> Result<(), Box<EvalAltResult>> {
|
|
|
|
let mut engine = Engine::new();
|
|
|
|
let ast = engine.compile("fn foo(x) { x + 1 }")?;
|
|
|
|
let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?;
|
|
|
|
|
|
|
|
engine.load_package(module);
|
|
|
|
|
|
|
|
assert_eq!(engine.eval::<INT>("foo(41)")?, 42);
|
2020-08-23 11:22:39 +02:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|