Keep only one call_fn, adds tuples of one and zero.

This commit is contained in:
Stephen Chung 2020-04-07 21:50:33 +08:00
parent e795a50ae2
commit 9f3646d9ec
4 changed files with 27 additions and 101 deletions

View File

@ -213,8 +213,7 @@ Compiling a script file is also supported:
let ast = engine.compile_file("hello_world.rhai".into())?; let ast = engine.compile_file("hello_world.rhai".into())?;
``` ```
Rhai also allows working _backwards_ from the other direction - i.e. calling a Rhai-scripted function from Rust - Rhai also allows working _backwards_ from the other direction - i.e. calling a Rhai-scripted function from Rust via `call_fn`.
via `call_fn` or its cousins `call_fn1` (one argument) and `call_fn0` (no argument).
```rust ```rust
// Define functions in a script. // Define functions in a script.
@ -239,20 +238,19 @@ let ast = engine.compile(true,
// A custom scope can also contain any variables/constants available to the functions // A custom scope can also contain any variables/constants available to the functions
let mut scope = Scope::new(); let mut scope = Scope::new();
// Evaluate a function defined in the script, passing arguments into the script as a tuple // Evaluate a function defined in the script, passing arguments into the script as a tuple.
// if there are more than one. Beware, arguments must be of the correct types because // Beware, arguments must be of the correct types because Rhai does not have built-in type conversions.
// Rhai does not have built-in type conversions. If arguments of the wrong types are passed, // If arguments of the wrong types are passed, the Engine will not find the function.
// the Engine will not find the function.
let result: i64 = engine.call_fn(&mut scope, &ast, "hello", ( String::from("abc"), 123_i64 ) )?; let result: i64 = engine.call_fn(&mut scope, &ast, "hello", ( String::from("abc"), 123_i64 ) )?;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// put arguments in a tuple // put arguments in a tuple
let result: i64 = engine.call_fn1(&mut scope, &ast, "hello", 123_i64)? let result: i64 = engine.call_fn(&mut scope, &ast, "hello", (123_i64,) )?
// ^^^^^^^^ use 'call_fn1' for one argument // ^^^^^^^^^^ tuple of one
let result: i64 = engine.call_fn0(&mut scope, &ast, "hello")? let result: i64 = engine.call_fn(&mut scope, &ast, "hello", () )?
// ^^^^^^^^ use 'call_fn0' for no arguments // ^^ unit = tuple of zero
``` ```
Evaluate expressions only Evaluate expressions only
@ -305,8 +303,8 @@ they even cannot be added together. This is very similar to Rust.
The default integer type is `i64`. If other integer types are not needed, it is possible to exclude them and make a The default integer type is `i64`. If other integer types are not needed, it is possible to exclude them and make a
smaller build with the [`only_i64`] feature. smaller build with the [`only_i64`] feature.
If only 32-bit integers are needed, enabling the [`only_i32`] feature will remove support for all integer types other than `i32`, If only 32-bit integers are needed, enabling the [`only_i32`] feature will remove support for all integer types other than `i32`, including `i64`.
including `i64`. This is useful on some 32-bit systems where using 64-bit integers incurs a performance penalty. This is useful on some 32-bit systems where using 64-bit integers incurs a performance penalty.
If no floating-point is needed or supported, use the [`no_float`] feature to remove it. If no floating-point is needed or supported, use the [`no_float`] feature to remove it.

View File

@ -831,79 +831,6 @@ impl<'e> Engine<'e> {
}) })
} }
/// Call a script function defined in an `AST` with no argument.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # #[cfg(not(feature = "no_stdlib"))]
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// let ast = engine.compile("fn num() { 42 + foo }")?;
///
/// let mut scope = Scope::new();
/// scope.push("foo", 42_i64);
///
/// // Call the script-defined function
/// let result: i64 = engine.call_fn0(&mut scope, &ast, "num")?;
///
/// assert_eq!(result, 84);
/// # }
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
pub fn call_fn0<T: Any + Clone>(
&self,
scope: &mut Scope,
ast: &AST,
name: &str,
) -> Result<T, EvalAltResult> {
self.call_fn_internal(scope, ast, name, vec![])
}
/// Call a script function defined in an `AST` with one argument.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), rhai::EvalAltResult> {
/// # #[cfg(not(feature = "no_stdlib"))]
/// # #[cfg(not(feature = "no_function"))]
/// # {
/// use rhai::{Engine, Scope};
///
/// let engine = Engine::new();
///
/// let ast = engine.compile("fn inc(x) { x + foo }")?;
///
/// let mut scope = Scope::new();
/// scope.push("foo", 42_i64);
///
/// // Call the script-defined function
/// let result: i64 = engine.call_fn1(&mut scope, &ast, "inc", 123_i64)?;
///
/// assert_eq!(result, 165);
/// # }
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_function"))]
pub fn call_fn1<A: Any + Clone, T: Any + Clone>(
&self,
scope: &mut Scope,
ast: &AST,
name: &str,
arg: A,
) -> Result<T, EvalAltResult> {
self.call_fn_internal(scope, ast, name, vec![arg.into_dynamic()])
}
/// Call a script function defined in an `AST` with multiple arguments. /// Call a script function defined in an `AST` with multiple arguments.
/// ///
/// # Example /// # Example
@ -917,15 +844,25 @@ impl<'e> Engine<'e> {
/// ///
/// let engine = Engine::new(); /// let engine = Engine::new();
/// ///
/// let ast = engine.compile("fn add(x, y) { len(x) + y + foo }")?; /// let ast = engine.compile(r"
/// fn add(x, y) { len(x) + y + foo }
/// fn add1(x) { len(x) + 1 + foo }
/// fn bar() { foo/2 }
/// ")?;
/// ///
/// let mut scope = Scope::new(); /// let mut scope = Scope::new();
/// scope.push("foo", 42_i64); /// scope.push("foo", 42_i64);
/// ///
/// // Call the script-defined function /// // Call the script-defined function
/// let result: i64 = engine.call_fn(&mut scope, &ast, "add", (String::from("abc"), 123_i64))?; /// let result: i64 = engine.call_fn(&mut scope, &ast, "add", ( String::from("abc"), 123_i64 ) )?;
///
/// assert_eq!(result, 168); /// assert_eq!(result, 168);
///
/// let result: i64 = engine.call_fn(&mut scope, &ast, "add1", ( String::from("abc"), ) )?;
/// // ^^^^^^^^^^^^^^^^^^^^^^^^ tuple of one
/// assert_eq!(result, 46);
///
/// let result: i64 = engine.call_fn(&mut scope, &ast, "bar", () )?;
/// assert_eq!(result, 21);
/// # } /// # }
/// # Ok(()) /// # Ok(())
/// # } /// # }
@ -938,17 +875,7 @@ impl<'e> Engine<'e> {
name: &str, name: &str,
args: A, args: A,
) -> Result<T, EvalAltResult> { ) -> Result<T, EvalAltResult> {
self.call_fn_internal(scope, ast, name, args.into_vec()) let mut arg_values = args.into_vec();
}
#[cfg(not(feature = "no_function"))]
fn call_fn_internal<T: Any + Clone>(
&self,
scope: &mut Scope,
ast: &AST,
name: &str,
mut arg_values: Vec<Dynamic>,
) -> Result<T, EvalAltResult> {
let mut args: Vec<_> = arg_values.iter_mut().map(Dynamic::as_mut).collect(); let mut args: Vec<_> = arg_values.iter_mut().map(Dynamic::as_mut).collect();
let fn_lib = Some(ast.1.as_ref()); let fn_lib = Some(ast.1.as_ref());
let pos = Position::none(); let pos = Position::none();

View File

@ -36,6 +36,7 @@ macro_rules! impl_args {
(@pop) => { (@pop) => {
}; };
(@pop $head:ident) => { (@pop $head:ident) => {
impl_args!();
}; };
(@pop $head:ident $(, $tail:ident)+) => { (@pop $head:ident $(, $tail:ident)+) => {
impl_args!($($tail),*); impl_args!($($tail),*);

View File

@ -44,10 +44,10 @@ fn test_call_fn() -> Result<(), EvalAltResult> {
let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?; let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?;
assert_eq!(r, 165); assert_eq!(r, 165);
let r: i64 = engine.call_fn1(&mut scope, &ast, "hello", 123 as INT)?; let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (123 as INT,))?;
assert_eq!(r, 5166); assert_eq!(r, 5166);
let r: i64 = engine.call_fn0(&mut scope, &ast, "hello")?; let r: i64 = engine.call_fn(&mut scope, &ast, "hello", ())?;
assert_eq!(r, 42); assert_eq!(r, 42);
assert_eq!( assert_eq!(