Add custom operators.

This commit is contained in:
Stephen Chung
2020-07-05 17:41:45 +08:00
parent 936a3ff44a
commit e390dd73e6
13 changed files with 326 additions and 139 deletions

View File

@@ -1,4 +1,4 @@
use rhai::{Engine, ParseErrorType};
use rhai::{Engine, EvalAltResult, ParseErrorType, RegisterFn, INT};
#[test]
fn test_tokens_disabled() {
@@ -18,3 +18,32 @@ fn test_tokens_disabled() {
ParseErrorType::BadInput(ref s) if s == "Unexpected '+='"
));
}
#[test]
fn test_tokens_custom_operator() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
// Register a custom operator called `foo` and give it
// a precedence of 140 (i.e. between +|- and *|/).
engine.register_custom_operator("foo", 140).unwrap();
// Register a binary function named `foo`
engine.register_fn("foo", |x: INT, y: INT| (x * y) - (x + y));
assert_eq!(
engine.eval_expression::<INT>("1 + 2 * 3 foo 4 - 5 / 6")?,
15
);
assert_eq!(
engine.eval::<INT>(
r"
fn foo(x, y) { y - x }
1 + 2 * 3 foo 4 - 5 / 6
"
)?,
-1
);
Ok(())
}