Allow binding of this pointer in FnPtr calls.

This commit is contained in:
Stephen Chung
2020-07-17 10:18:07 +08:00
parent 197f5d370f
commit d119e13b79
9 changed files with 267 additions and 70 deletions

View File

@@ -116,7 +116,7 @@ fn test_anonymous_fn() -> Result<(), Box<EvalAltResult>> {
#[test]
#[cfg(not(feature = "no_object"))]
fn test_fn_ptr() -> Result<(), Box<EvalAltResult>> {
fn test_fn_ptr_raw() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_raw_fn(

80
tests/fn_ptr.rs Normal file
View File

@@ -0,0 +1,80 @@
use rhai::{Engine, EvalAltResult, RegisterFn, INT};
#[test]
fn test_fn_ptr() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.register_fn("bar", |x: &mut INT, y: INT| *x += y);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>(
r#"
let f = Fn("bar");
let x = 40;
f.call(x, 2);
x
"#
)?,
40
);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>(
r#"
let f = Fn("bar");
let x = 40;
x.call(f, 2);
x
"#
)?,
42
);
assert_eq!(
engine.eval::<INT>(
r#"
let f = Fn("bar");
let x = 40;
call(f, x, 2);
x
"#
)?,
42
);
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<INT>(
r#"
fn foo(x) { this += x; }
let f = Fn("foo");
let x = 40;
x.call(f, 2);
x
"#
)?,
42
);
#[cfg(not(feature = "no_function"))]
assert!(matches!(
*engine
.eval::<INT>(
r#"
fn foo(x) { this += x; }
let f = Fn("foo");
call(f, 2);
x
"#
)
.expect_err("should error"),
EvalAltResult::ErrorInFunctionCall(fn_name, err, _) if fn_name == "foo" && matches!(*err, EvalAltResult::ErrorUnboundedThis(_))
));
Ok(())
}