2020-03-02 15:11:56 +01:00
|
|
|
use rhai::{Engine, EvalAltResult, Scope};
|
2017-11-03 17:58:51 +01:00
|
|
|
|
|
|
|
#[test]
|
2020-03-02 15:11:56 +01:00
|
|
|
fn test_var_scope() -> Result<(), EvalAltResult> {
|
2017-11-03 17:58:51 +01:00
|
|
|
let mut engine = Engine::new();
|
2019-09-18 12:21:07 +02:00
|
|
|
let mut scope = Scope::new();
|
2017-11-03 17:58:51 +01:00
|
|
|
|
2020-03-10 02:30:12 +01:00
|
|
|
engine.eval_with_scope::<()>(&mut scope, false, "let x = 4 + 5")?;
|
|
|
|
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, false, "x")?, 9);
|
|
|
|
engine.eval_with_scope::<()>(&mut scope, false, "x = x + 1; x = x + 2;")?;
|
|
|
|
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, false, "x")?, 12);
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval_with_scope::<()>(&mut scope, false, "{let x = 3}")?,
|
|
|
|
()
|
|
|
|
);
|
|
|
|
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, false, "x")?, 12);
|
2017-11-03 17:58:51 +01:00
|
|
|
|
2020-03-02 15:11:56 +01:00
|
|
|
Ok(())
|
2017-11-03 17:58:51 +01:00
|
|
|
}
|
2020-03-03 08:20:20 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_scope_eval() -> Result<(), EvalAltResult> {
|
|
|
|
let mut engine = Engine::new();
|
|
|
|
|
|
|
|
// First create the state
|
|
|
|
let mut scope = Scope::new();
|
|
|
|
|
|
|
|
// Then push some initialized variables into the state
|
|
|
|
// NOTE: Remember the default numbers used by Rhai are i64 and f64.
|
|
|
|
// Better stick to them or it gets hard to work with other variables in the script.
|
2020-03-07 03:15:42 +01:00
|
|
|
scope.push("y", 42_i64);
|
|
|
|
scope.push("z", 999_i64);
|
2020-03-03 08:20:20 +01:00
|
|
|
|
|
|
|
// First invocation
|
|
|
|
engine
|
2020-03-10 02:30:12 +01:00
|
|
|
.eval_with_scope::<()>(&mut scope, false, " let x = 4 + 5 - y + z; y = 1;")
|
2020-03-03 08:20:20 +01:00
|
|
|
.expect("y and z not found?");
|
|
|
|
|
|
|
|
// Second invocation using the same state
|
2020-03-10 02:30:12 +01:00
|
|
|
let result = engine.eval_with_scope::<i64>(&mut scope, false, "x")?;
|
2020-03-09 14:09:53 +01:00
|
|
|
|
|
|
|
println!("result: {}", result); // should print 966
|
2020-03-03 08:20:20 +01:00
|
|
|
|
|
|
|
// Variable y is changed in the script
|
|
|
|
assert_eq!(scope.get_value::<i64>("y").unwrap(), 1);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|