rhai/tests/packages.rs

58 lines
1.7 KiB
Rust
Raw Normal View History

2022-08-18 11:22:56 +02:00
use rhai::packages::{Package, StandardPackage as SSS};
use rhai::{def_package, Engine, EvalAltResult, Module, Scope, INT};
2022-08-18 15:36:00 +02:00
#[cfg(not(feature = "no_module"))]
#[cfg(not(feature = "no_custom_syntax"))]
#[test]
fn test_packages() -> Result<(), Box<EvalAltResult>> {
2022-08-18 15:36:00 +02:00
def_package! {
/// My custom package.
MyPackage(m) : SSS {
m.set_native_fn("hello", |x: INT| Ok(x + 1));
m.set_native_fn("@", |x: INT, y: INT| Ok(x * x + y * y));
} |> |engine| {
engine.register_custom_operator("@", 160).unwrap();
}
}
2022-08-18 11:22:56 +02:00
let pkg = MyPackage::new();
let make_call = |x: INT| -> Result<INT, Box<EvalAltResult>> {
// Create a raw Engine - extremely cheap.
let mut engine = Engine::new_raw();
2020-12-22 16:45:14 +01:00
// Register packages - cheap.
2022-08-18 11:22:56 +02:00
pkg.register_into_engine(&mut engine);
pkg.register_into_engine_as(&mut engine, "foo");
// Create custom scope - cheap.
let mut scope = Scope::new();
// Push variable into scope - relatively cheap.
scope.push("x", x);
// Evaluate script.
2022-08-18 15:16:42 +02:00
2022-08-18 15:36:00 +02:00
engine.eval_with_scope::<INT>(&mut scope, "hello(x) @ foo::hello(x)")
};
2022-08-18 11:22:56 +02:00
assert_eq!(make_call(42)?, 3698);
2020-09-11 16:32:59 +02:00
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();
2020-09-25 13:07:24 +02:00
let ast = engine.compile("fn foo(x) { x + 1 } fn bar(x) { foo(x) + 1 }")?;
2020-09-11 16:32:59 +02:00
let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?;
engine.register_global_module(module.into());
2020-09-11 16:32:59 +02:00
assert_eq!(engine.eval::<INT>("foo(41)")?, 42);
2020-09-25 13:07:24 +02:00
assert_eq!(engine.eval::<INT>("bar(40)")?, 42);
Ok(())
}