pub struct Engine { /* private fields */ }
Expand description
Implementations§
Source§impl Engine
impl Engine
Sourcepub fn eval<T: Variant + Clone>(
&self,
script: &str,
) -> Result<T, Box<EvalAltResult>>
pub fn eval<T: Variant + Clone>( &self, script: &str, ) -> Result<T, Box<EvalAltResult>>
Evaluate a string as a script, returning the result value or an error.
§Example
use rhai::Engine;
let engine = Engine::new();
assert_eq!(engine.eval::<i64>("40 + 2")?, 42);
Sourcepub fn eval_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope<'_>,
script: &str,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_with_scope<T: Variant + Clone>( &self, scope: &mut Scope<'_>, script: &str, ) -> Result<T, Box<EvalAltResult>>
Evaluate a string as a script with own scope, returning the result value or an error.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions.
This allows functions to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x += 2; x")?, 42);
assert_eq!(engine.eval_with_scope::<i64>(&mut scope, "x += 2; x")?, 44);
// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);
Sourcepub fn eval_expression<T: Variant + Clone>(
&self,
script: &str,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_expression<T: Variant + Clone>( &self, script: &str, ) -> Result<T, Box<EvalAltResult>>
Evaluate a string containing an expression, returning the result value or an error.
§Example
use rhai::Engine;
let engine = Engine::new();
assert_eq!(engine.eval_expression::<i64>("40 + 2")?, 42);
Sourcepub fn eval_expression_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope<'_>,
script: &str,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_expression_with_scope<T: Variant + Clone>( &self, scope: &mut Scope<'_>, script: &str, ) -> Result<T, Box<EvalAltResult>>
Evaluate a string containing an expression with own scope, returning the result value or an error.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);
assert_eq!(engine.eval_expression_with_scope::<i64>(&mut scope, "x + 2")?, 42);
Sourcepub fn eval_ast_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope<'_>,
ast: &AST,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_ast_with_scope<T: Variant + Clone>( &self, scope: &mut Scope<'_>, ast: &AST, ) -> Result<T, Box<EvalAltResult>>
Evaluate an AST
with own scope, returning the result value or an error.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);
// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("x += 2; x")?;
// Evaluate it
assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 42);
assert_eq!(engine.eval_ast_with_scope::<i64>(&mut scope, &ast)?, 44);
// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 44);
Source§impl Engine
impl Engine
Sourcepub fn run(&self, script: &str) -> Result<(), Box<EvalAltResult>>
pub fn run(&self, script: &str) -> Result<(), Box<EvalAltResult>>
Evaluate a string as a script.
§Example
use rhai::Engine;
let engine = Engine::new();
engine.run("print(40 + 2);")?;
Sourcepub fn run_with_scope(
&self,
scope: &mut Scope<'_>,
script: &str,
) -> Result<(), Box<EvalAltResult>>
pub fn run_with_scope( &self, scope: &mut Scope<'_>, script: &str, ) -> Result<(), Box<EvalAltResult>>
Evaluate a string as a script with own scope.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions.
This allows functions to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);
engine.run_with_scope(&mut scope, "x += 2; print(x);")?;
// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 42);
Sourcepub fn run_ast_with_scope(
&self,
scope: &mut Scope<'_>,
ast: &AST,
) -> Result<(), Box<EvalAltResult>>
pub fn run_ast_with_scope( &self, scope: &mut Scope<'_>, ast: &AST, ) -> Result<(), Box<EvalAltResult>>
Evaluate an AST
with own scope.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 40_i64);
// Compile a script to an AST and store it for later evaluation
let ast = engine.compile("x += 2; x")?;
// Evaluate it
engine.run_ast_with_scope(&mut scope, &ast)?;
// The variable in the scope is modified
assert_eq!(scope.get_value::<i64>("x").expect("variable x should exist"), 42);
Source§impl Engine
impl Engine
Sourcepub fn compile_with_scope(
&self,
scope: &Scope<'_>,
script: impl AsRef<str>,
) -> Result<AST, ParseError>
pub fn compile_with_scope( &self, scope: &Scope<'_>, script: impl AsRef<str>, ) -> Result<AST, ParseError>
Compile a string into an AST
using own scope, which can be used later for evaluation.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions. This allows functions
to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope, OptimizationLevel};
let mut engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64); // 'x' is a constant
// Compile a script to an AST and store it for later evaluation.
// Notice that `Full` optimization is on, so constants are folded
// into function calls and operators.
let ast = engine.compile_with_scope(&mut scope,
"if x > 40 { x } else { 0 }" // all 'x' are replaced with 42
)?;
// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist. Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
Sourcepub fn compile_into_self_contained(
&self,
scope: &Scope<'_>,
script: impl AsRef<str>,
) -> Result<AST, Box<EvalAltResult>>
pub fn compile_into_self_contained( &self, scope: &Scope<'_>, script: impl AsRef<str>, ) -> Result<AST, Box<EvalAltResult>>
Compile a string into an AST
using own scope, which can be used later for evaluation,
embedding all imported modules.
Not available under no_module
.
Modules referred by import
statements containing literal string paths are eagerly resolved
via the current module resolver and embedded into the resultant
AST
. When it is evaluated later, import
statement directly recall pre-resolved
modules and the resolution process is not performed again.
Sourcepub fn compile_scripts_with_scope<S: AsRef<str>>(
&self,
scope: &Scope<'_>,
scripts: impl AsRef<[S]>,
) -> Result<AST, ParseError>
pub fn compile_scripts_with_scope<S: AsRef<str>>( &self, scope: &Scope<'_>, scripts: impl AsRef<[S]>, ) -> Result<AST, ParseError>
When passed a list of strings, first join the strings into one large script, and then
compile them into an AST
using own scope, which can be used later for evaluation.
The scope is useful for passing constants into the script for optimization when using
OptimizationLevel::Full
.
§Note
All strings are simply parsed one after another with nothing inserted in between, not even a newline or space.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions. This allows functions
to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope, OptimizationLevel};
let mut engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64); // 'x' is a constant
// Compile a script made up of script segments to an AST and store it for later evaluation.
// Notice that `Full` optimization is on, so constants are folded
// into function calls and operators.
let ast = engine.compile_scripts_with_scope(&mut scope, &[
"if x > 40", // all 'x' are replaced with 42
"{ x } el",
"se { 0 }" // segments do not need to be valid scripts!
])?;
// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist. Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
Sourcepub fn compile_expression(
&self,
script: impl AsRef<str>,
) -> Result<AST, ParseError>
pub fn compile_expression( &self, script: impl AsRef<str>, ) -> Result<AST, ParseError>
Compile a string containing an expression into an AST
,
which can be used later for evaluation.
§Example
use rhai::Engine;
let engine = Engine::new();
// Compile a script to an AST and store it for later evaluation
let ast = engine.compile_expression("40 + 2")?;
for _ in 0..42 {
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
}
Sourcepub fn compile_expression_with_scope(
&self,
scope: &Scope<'_>,
script: impl AsRef<str>,
) -> Result<AST, ParseError>
pub fn compile_expression_with_scope( &self, scope: &Scope<'_>, script: impl AsRef<str>, ) -> Result<AST, ParseError>
Compile a string containing an expression into an AST
using own scope,
which can be used later for evaluation.
§Example
use rhai::{Engine, Scope, OptimizationLevel};
let mut engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 10_i64); // 'x' is a constant
// Compile a script to an AST and store it for later evaluation.
let ast = engine.compile_expression_with_scope(&mut scope,
"2 + (x + x) * 2" // all 'x' are replaced with 10
)?;
// Normally this would have failed because no scope is passed into the 'eval_ast'
// call and so the variable 'x' does not exist. Here, it passes because the script
// has been optimized and all references to 'x' are already gone.
assert_eq!(engine.eval_ast::<i64>(&ast)?, 42);
Source§impl Engine
impl Engine
Sourcepub fn parse_json(
&self,
json: impl AsRef<str>,
has_null: bool,
) -> Result<Map, Box<EvalAltResult>>
pub fn parse_json( &self, json: impl AsRef<str>, has_null: bool, ) -> Result<Map, Box<EvalAltResult>>
Parse a JSON string into an object map.
This is a light-weight alternative to using, say, serde_json
to deserialize the JSON.
Not available under no_object
.
The JSON string must be an object hash. It cannot be a simple primitive value.
Set has_null
to true
in order to map null
values to ()
.
Setting it to false
causes a syntax error for any null
value.
JSON sub-objects are handled transparently.
This function can be used together with format_map_as_json
to work with JSON texts
without using the serde_json
crate (which is heavy).
§Example
use rhai::{Engine, Map};
let engine = Engine::new();
let map = engine.parse_json(r#"
{
"a": 123,
"b": 42,
"c": {
"x": false,
"y": true,
"z": '$'
},
"d": null
}"#, true)?;
assert_eq!(map.len(), 4);
assert_eq!(map["a"].as_int().expect("a should exist"), 123);
assert_eq!(map["b"].as_int().expect("b should exist"), 42);
assert_eq!(map["d"].as_unit().expect("d should exist"), ());
let c = map["c"].as_map_ref().expect("c should exist");
assert_eq!(c["x"].as_bool().expect("x should be bool"), false);
assert_eq!(c["y"].as_bool().expect("y should be bool"), true);
assert_eq!(c["z"].as_char().expect("z should be char"), '$');
Source§impl Engine
impl Engine
Sourcepub fn compile_file(&self, path: PathBuf) -> Result<AST, Box<EvalAltResult>>
pub fn compile_file(&self, path: PathBuf) -> Result<AST, Box<EvalAltResult>>
Compile a script file into an AST
, which can be used later for evaluation.
Not available under no_std
or WASM
.
§Example
use rhai::Engine;
let engine = Engine::new();
// Compile a script file to an AST and store it for later evaluation.
// Notice that a PathBuf is required which can easily be constructed from a string.
let ast = engine.compile_file("script.rhai".into())?;
for _ in 0..42 {
engine.eval_ast::<i64>(&ast)?;
}
Sourcepub fn compile_file_with_scope(
&self,
scope: &Scope<'_>,
path: PathBuf,
) -> Result<AST, Box<EvalAltResult>>
pub fn compile_file_with_scope( &self, scope: &Scope<'_>, path: PathBuf, ) -> Result<AST, Box<EvalAltResult>>
Compile a script file into an AST
using own scope, which can be used later for evaluation.
Not available under no_std
or WASM
.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions.
This allows functions to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope, OptimizationLevel};
let mut engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push_constant("x", 42_i64); // 'x' is a constant
// Compile a script to an AST and store it for later evaluation.
// Notice that a PathBuf is required which can easily be constructed from a string.
let ast = engine.compile_file_with_scope(&scope, "script.rhai".into())?;
let result = engine.eval_ast::<i64>(&ast)?;
Sourcepub fn eval_file<T: Variant + Clone>(
&self,
path: PathBuf,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_file<T: Variant + Clone>( &self, path: PathBuf, ) -> Result<T, Box<EvalAltResult>>
Evaluate a script file, returning the result value or an error.
Not available under no_std
or WASM
.
§Example
use rhai::Engine;
let engine = Engine::new();
// Notice that a PathBuf is required which can easily be constructed from a string.
let result = engine.eval_file::<i64>("script.rhai".into())?;
Sourcepub fn eval_file_with_scope<T: Variant + Clone>(
&self,
scope: &mut Scope<'_>,
path: PathBuf,
) -> Result<T, Box<EvalAltResult>>
pub fn eval_file_with_scope<T: Variant + Clone>( &self, scope: &mut Scope<'_>, path: PathBuf, ) -> Result<T, Box<EvalAltResult>>
Evaluate a script file with own scope, returning the result value or an error.
Not available under no_std
or WASM
.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions.
This allows functions to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 42_i64);
// Notice that a PathBuf is required which can easily be constructed from a string.
let result = engine.eval_file_with_scope::<i64>(&mut scope, "script.rhai".into())?;
Sourcepub fn run_file(&self, path: PathBuf) -> Result<(), Box<EvalAltResult>>
pub fn run_file(&self, path: PathBuf) -> Result<(), Box<EvalAltResult>>
Evaluate a file.
Not available under no_std
or WASM
.
§Example
use rhai::Engine;
let engine = Engine::new();
// Notice that a PathBuf is required which can easily be constructed from a string.
engine.run_file("script.rhai".into())?;
Sourcepub fn run_file_with_scope(
&self,
scope: &mut Scope<'_>,
path: PathBuf,
) -> Result<(), Box<EvalAltResult>>
pub fn run_file_with_scope( &self, scope: &mut Scope<'_>, path: PathBuf, ) -> Result<(), Box<EvalAltResult>>
Evaluate a file with own scope.
Not available under no_std
or WASM
.
§Constants Propagation
If not OptimizationLevel::None
, constants defined within
the scope are propagated throughout the script including functions.
This allows functions to be optimized based on dynamic global constants.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
// Create initialized scope
let mut scope = Scope::new();
scope.push("x", 42_i64);
// Notice that a PathBuf is required which can easily be constructed from a string.
engine.run_file_with_scope(&mut scope, "script.rhai".into())?;
Source§impl Engine
impl Engine
Sourcepub fn register_fn<A: 'static, const N: usize, const X: bool, R: Variant + Clone, const F: bool>(
&mut self,
name: impl AsRef<str> + Into<Identifier>,
func: impl RhaiNativeFunc<A, N, X, R, F> + SendSync + 'static,
) -> &mut Self
pub fn register_fn<A: 'static, const N: usize, const X: bool, R: Variant + Clone, const F: bool>( &mut self, name: impl AsRef<str> + Into<Identifier>, func: impl RhaiNativeFunc<A, N, X, R, F> + SendSync + 'static, ) -> &mut Self
Register a custom function with the Engine
.
§Assumptions
-
Accessibility: The function namespace is
FnNamespace::Global
. -
Purity: The function is assumed to be pure unless it is a property setter or an index setter.
-
Volatility: The function is assumed to be non-volatile – i.e. it guarantees the same result for the same input(s).
§Example
use rhai::Engine;
// Normal function
fn add(x: i64, y: i64) -> i64 {
x + y
}
let mut engine = Engine::new();
engine.register_fn("add", add);
assert_eq!(engine.eval::<i64>("add(40, 2)")?, 42);
// You can also register a closure.
engine.register_fn("sub", |x: i64, y: i64| x - y );
assert_eq!(engine.eval::<i64>("sub(44, 2)")?, 42);
Sourcepub fn register_raw_fn<T: Variant + Clone>(
&mut self,
name: impl AsRef<str> + Into<Identifier>,
arg_types: impl AsRef<[TypeId]>,
func: impl Fn(NativeCallContext<'_>, &mut [&'_ mut Dynamic]) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
pub fn register_raw_fn<T: Variant + Clone>( &mut self, name: impl AsRef<str> + Into<Identifier>, arg_types: impl AsRef<[TypeId]>, func: impl Fn(NativeCallContext<'_>, &mut [&'_ mut Dynamic]) -> Result<T, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
Register a function of the Engine
.
§WARNING - Low Level API
This function is very low level. It takes a list of TypeId
’s
indicating the actual types of the parameters.
§Arguments
Arguments are simply passed in as a mutable array of &mut Dynamic
.
The arguments are guaranteed to be of the correct types matching the TypeId
’s.
To access a primary argument value (i.e. cloning is cheap), use: args[n].as_xxx().unwrap()
To access an argument value and avoid cloning, use args[n].take().cast::<T>()
.
Notice that this will consume the argument, replacing it with ()
.
To access the first mutable parameter, use args.get_mut(0).unwrap()
Sourcepub fn register_type<T: Variant + Clone>(&mut self) -> &mut Self
pub fn register_type<T: Variant + Clone>(&mut self) -> &mut Self
Register a custom type for use with the Engine
.
The type must implement Clone
.
§Example
#[derive(Debug, Clone, Eq, PartialEq)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
fn update(&mut self, offset: i64) {
self.field += offset;
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine
.register_type::<TestStruct>()
.register_fn("new_ts", TestStruct::new)
// Use `register_fn` to register methods on the type.
.register_fn("update", TestStruct::update);
assert_eq!(
engine.eval::<TestStruct>("let x = new_ts(); x.update(41); x")?,
TestStruct { field: 42 }
);
Sourcepub fn register_type_with_name<T: Variant + Clone>(
&mut self,
name: &str,
) -> &mut Self
pub fn register_type_with_name<T: Variant + Clone>( &mut self, name: &str, ) -> &mut Self
Register a custom type for use with the Engine
, with a pretty-print name
for the type_of
function. The type must implement Clone
.
§Example
#[derive(Clone)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine
.register_type::<TestStruct>()
.register_fn("new_ts", TestStruct::new);
assert_eq!(
engine.eval::<String>("let x = new_ts(); type_of(x)")?,
"rust_out::TestStruct"
);
// Re-register the custom type with a name.
engine.register_type_with_name::<TestStruct>("Hello");
assert_eq!(
engine.eval::<String>("let x = new_ts(); type_of(x)")?,
"Hello"
);
Sourcepub fn register_type_with_name_raw(
&mut self,
type_path: impl Into<Identifier>,
name: impl Into<Identifier>,
) -> &mut Self
pub fn register_type_with_name_raw( &mut self, type_path: impl Into<Identifier>, name: impl Into<Identifier>, ) -> &mut Self
Sourcepub fn register_iterator<T>(&mut self) -> &mut Self
pub fn register_iterator<T>(&mut self) -> &mut Self
Register a type iterator for an iterable type with the Engine
.
This is an advanced API.
Sourcepub fn register_iterator_result<T, R>(&mut self) -> &mut Self
pub fn register_iterator_result<T, R>(&mut self) -> &mut Self
Register a fallible type iterator for an iterable type with the Engine
.
This is an advanced API.
Sourcepub fn register_get<T: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>(
&mut self,
name: impl AsRef<str>,
get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X, R, F> + SendSync + 'static,
) -> &mut Self
pub fn register_get<T: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>( &mut self, name: impl AsRef<str>, get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X, R, F> + SendSync + 'static, ) -> &mut Self
Register a getter function for a member of a registered type with the Engine
.
The function signature must start with &mut self
and not &self
.
Not available under no_object
.
§Example
#[derive(Clone)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
// Even a getter must start with `&mut self` and not `&self`.
fn get_field(&mut self) -> i64 {
self.field
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine
.register_type::<TestStruct>()
.register_fn("new_ts", TestStruct::new)
// Register a getter on a property (notice it doesn't have to be the same name).
.register_get("xyz", TestStruct::get_field);
assert_eq!(engine.eval::<i64>("let a = new_ts(); a.xyz")?, 1);
Sourcepub fn register_set<T: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>(
&mut self,
name: impl AsRef<str>,
set_fn: impl RhaiNativeFunc<(Mut<T>, R), 2, X, (), F> + SendSync + 'static,
) -> &mut Self
pub fn register_set<T: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>( &mut self, name: impl AsRef<str>, set_fn: impl RhaiNativeFunc<(Mut<T>, R), 2, X, (), F> + SendSync + 'static, ) -> &mut Self
Register a setter function for a member of a registered type with the Engine
.
Not available under no_object
.
§Example
#[derive(Debug, Clone, Eq, PartialEq)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
fn set_field(&mut self, new_val: i64) {
self.field = new_val;
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine
.register_type::<TestStruct>()
.register_fn("new_ts", TestStruct::new)
// Register a setter on a property (notice it doesn't have to be the same name)
.register_set("xyz", TestStruct::set_field);
// Notice that, with a getter, there is no way to get the property value
assert_eq!(
engine.eval::<TestStruct>("let a = new_ts(); a.xyz = 42; a")?,
TestStruct { field: 42 }
);
Sourcepub fn register_get_set<T: Variant + Clone, const X1: bool, const X2: bool, R: Variant + Clone, const F1: bool, const F2: bool>(
&mut self,
name: impl AsRef<str>,
get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X1, R, F1> + SendSync + 'static,
set_fn: impl RhaiNativeFunc<(Mut<T>, R), 2, X2, (), F2> + SendSync + 'static,
) -> &mut Self
pub fn register_get_set<T: Variant + Clone, const X1: bool, const X2: bool, R: Variant + Clone, const F1: bool, const F2: bool>( &mut self, name: impl AsRef<str>, get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X1, R, F1> + SendSync + 'static, set_fn: impl RhaiNativeFunc<(Mut<T>, R), 2, X2, (), F2> + SendSync + 'static, ) -> &mut Self
Short-hand for registering both getter and setter functions
of a registered type with the Engine
.
All function signatures must start with &mut self
and not &self
.
Not available under no_object
.
§Example
#[derive(Clone)]
struct TestStruct {
field: i64
}
impl TestStruct {
fn new() -> Self {
Self { field: 1 }
}
// Even a getter must start with `&mut self` and not `&self`.
fn get_field(&mut self) -> i64 {
self.field
}
fn set_field(&mut self, new_val: i64) {
self.field = new_val;
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine
.register_type::<TestStruct>()
.register_fn("new_ts", TestStruct::new)
// Register both a getter and a setter on a property
// (notice it doesn't have to be the same name)
.register_get_set("xyz", TestStruct::get_field, TestStruct::set_field);
assert_eq!(engine.eval::<i64>("let a = new_ts(); a.xyz = 42; a.xyz")?, 42);
Sourcepub fn register_indexer_get<T: Variant + Clone, IDX: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>(
&mut self,
get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X, R, F> + SendSync + 'static,
) -> &mut Self
pub fn register_indexer_get<T: Variant + Clone, IDX: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>( &mut self, get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X, R, F> + SendSync + 'static, ) -> &mut Self
Register an index getter for a custom type with the Engine
.
The function signature must start with &mut self
and not &self
.
Not available under both no_index
and no_object
.
§Panics
Panics if the type is Array
, Map
, String
,
ImmutableString
, &str
or INT
.
Indexers for arrays, object maps, strings and integers cannot be registered.
§Example
#[derive(Clone)]
struct TestStruct {
fields: Vec<i64>
}
impl TestStruct {
fn new() -> Self {
Self { fields: vec![1, 2, 3, 4, 5] }
}
// Even a getter must start with `&mut self` and not `&self`.
fn get_field(&mut self, index: i64) -> i64 {
self.fields[index as usize]
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine.register_type::<TestStruct>();
engine
.register_fn("new_ts", TestStruct::new)
// Register an indexer.
.register_indexer_get(TestStruct::get_field);
assert_eq!(engine.eval::<i64>("let a = new_ts(); a[2]")?, 3);
Sourcepub fn register_indexer_set<T: Variant + Clone, IDX: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>(
&mut self,
set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X, (), F> + SendSync + 'static,
) -> &mut Self
pub fn register_indexer_set<T: Variant + Clone, IDX: Variant + Clone, const X: bool, R: Variant + Clone, const F: bool>( &mut self, set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X, (), F> + SendSync + 'static, ) -> &mut Self
Register an index setter for a custom type with the Engine
.
Not available under both no_index
and no_object
.
§Panics
Panics if the type is Array
, Map
, String
,
ImmutableString
, &str
or INT
.
Indexers for arrays, object maps, strings and integers cannot be registered.
§Example
#[derive(Clone)]
struct TestStruct {
fields: Vec<i64>
}
impl TestStruct {
fn new() -> Self {
Self { fields: vec![1, 2, 3, 4, 5] }
}
fn set_field(&mut self, index: i64, value: i64) {
self.fields[index as usize] = value;
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine.register_type::<TestStruct>();
engine
.register_fn("new_ts", TestStruct::new)
// Register an indexer.
.register_indexer_set(TestStruct::set_field);
let result = engine.eval::<TestStruct>("let a = new_ts(); a[2] = 42; a")?;
assert_eq!(result.fields[2], 42);
Sourcepub fn register_indexer_get_set<T: Variant + Clone, IDX: Variant + Clone, const X1: bool, const X2: bool, R: Variant + Clone, const F1: bool, const F2: bool>(
&mut self,
get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X1, R, F1> + SendSync + 'static,
set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X2, (), F2> + SendSync + 'static,
) -> &mut Self
pub fn register_indexer_get_set<T: Variant + Clone, IDX: Variant + Clone, const X1: bool, const X2: bool, R: Variant + Clone, const F1: bool, const F2: bool>( &mut self, get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X1, R, F1> + SendSync + 'static, set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X2, (), F2> + SendSync + 'static, ) -> &mut Self
Short-hand for registering both index getter and setter functions for a custom type with the Engine
.
Not available under both no_index
and no_object
.
§Panics
Panics if the type is Array
, Map
, String
,
ImmutableString
, &str
or INT
.
Indexers for arrays, object maps, strings and integers cannot be registered.
§Example
#[derive(Clone)]
struct TestStruct {
fields: Vec<i64>
}
impl TestStruct {
fn new() -> Self {
Self { fields: vec![1, 2, 3, 4, 5] }
}
// Even a getter must start with `&mut self` and not `&self`.
fn get_field(&mut self, index: i64) -> i64 {
self.fields[index as usize]
}
fn set_field(&mut self, index: i64, value: i64) {
self.fields[index as usize] = value;
}
}
use rhai::Engine;
let mut engine = Engine::new();
// Register API for the custom type.
engine.register_type::<TestStruct>();
engine
.register_fn("new_ts", TestStruct::new)
// Register an indexer.
.register_indexer_get_set(TestStruct::get_field, TestStruct::set_field);
assert_eq!(engine.eval::<i64>("let a = new_ts(); a[2] = 42; a[2]")?, 42);
Sourcepub fn register_global_module(&mut self, module: Shared<Module>) -> &mut Self
pub fn register_global_module(&mut self, module: Shared<Module>) -> &mut Self
Register a shared Module
into the global namespace of Engine
.
All functions and type iterators are automatically available to scripts without namespace qualifications.
Sub-modules and variables are ignored.
When searching for functions, modules loaded later are preferred. In other words, loaded modules are searched in reverse order.
Sourcepub fn register_static_module(
&mut self,
name: impl AsRef<str>,
module: Shared<Module>,
) -> &mut Self
pub fn register_static_module( &mut self, name: impl AsRef<str>, module: Shared<Module>, ) -> &mut Self
Register a shared Module
as a static module namespace with the Engine
.
Functions marked FnNamespace::Global
and type iterators are exposed to scripts without
namespace qualifications.
Not available under no_module
.
§Example
use rhai::{Engine, Shared, Module};
let mut engine = Engine::new();
// Create the module
let mut module = Module::new();
module.set_native_fn("calc", |x: i64| Ok(x + 1));
let module: Shared<Module> = module.into();
engine
// Register the module as a fixed sub-module
.register_static_module("foo::bar::baz", module.clone())
// Multiple registrations to the same partial path is also OK!
.register_static_module("foo::bar::hello", module.clone())
.register_static_module("CalcService", module);
assert_eq!(engine.eval::<i64>("foo::bar::baz::calc(41)")?, 42);
assert_eq!(engine.eval::<i64>("foo::bar::hello::calc(41)")?, 42);
assert_eq!(engine.eval::<i64>("CalcService::calc(41)")?, 42);
Sourcepub fn gen_fn_signatures(&self, include_standard_packages: bool) -> Vec<String>
pub fn gen_fn_signatures(&self, include_standard_packages: bool) -> Vec<String>
(metadata) Generate a list of all registered functions.
Exported under the metadata
feature only.
Functions from the following sources are included, in order:
- Functions registered into the global namespace
- Functions in registered sub-modules
- Functions in registered packages
- Functions in standard packages (optional)
Sourcepub fn collect_fn_metadata<T>(
&self,
ctx: Option<&NativeCallContext<'_>>,
mapper: impl Fn(FuncInfo<'_>) -> Option<T> + Copy,
include_standard_packages: bool,
) -> Vec<T>
pub fn collect_fn_metadata<T>( &self, ctx: Option<&NativeCallContext<'_>>, mapper: impl Fn(FuncInfo<'_>) -> Option<T> + Copy, include_standard_packages: bool, ) -> Vec<T>
Collect the FuncInfo
of all functions, native or script-defined,
mapping them into any type.
Exported under the internals
feature only.
Return None
from the mapper
to skip a function.
Functions from the following sources are included, in order:
- Functions defined in the current script (if any)
- Functions registered into the global namespace
- Functions in registered packages
- Functions in standard packages (optional)
- Functions defined in modules
import
-ed by the current script (if any) - Functions in registered sub-modules
Source§impl Engine
impl Engine
Sourcepub fn call_fn<T: Variant + Clone>(
&self,
scope: &mut Scope<'_>,
ast: &AST,
name: impl AsRef<str>,
args: impl FuncArgs,
) -> Result<T, Box<EvalAltResult>>
pub fn call_fn<T: Variant + Clone>( &self, scope: &mut Scope<'_>, ast: &AST, name: impl AsRef<str>, args: impl FuncArgs, ) -> Result<T, Box<EvalAltResult>>
Call a script function defined in an AST
with multiple arguments.
Not available under no_function
.
The AST
is evaluated before calling the function.
This allows a script to load the necessary modules.
This is usually desired. If not, use call_fn_with_options
instead.
§Example
use rhai::{Engine, Scope};
let engine = Engine::new();
let ast = engine.compile("
fn add(x, y) { len(x) + y + foo }
fn add1(x) { len(x) + 1 + foo }
fn bar() { foo/2 }
")?;
let mut scope = Scope::new();
scope.push("foo", 42_i64);
// Call the script-defined function
let result = engine.call_fn::<i64>(&mut scope, &ast, "add", ( "abc", 123_i64 ) )?;
assert_eq!(result, 168);
let result = engine.call_fn::<i64>(&mut scope, &ast, "add1", ( "abc", ) )?;
// ^^^^^^^^^^ tuple of one
assert_eq!(result, 46);
let result = engine.call_fn::<i64>(&mut scope, &ast, "bar", () )?;
assert_eq!(result, 21);
Sourcepub fn call_fn_with_options<T: Variant + Clone>(
&self,
options: CallFnOptions<'_>,
scope: &mut Scope<'_>,
ast: &AST,
name: impl AsRef<str>,
args: impl FuncArgs,
) -> Result<T, Box<EvalAltResult>>
pub fn call_fn_with_options<T: Variant + Clone>( &self, options: CallFnOptions<'_>, scope: &mut Scope<'_>, ast: &AST, name: impl AsRef<str>, args: impl FuncArgs, ) -> Result<T, Box<EvalAltResult>>
Call a script function defined in an AST
with multiple Dynamic
arguments.
Options are provided via the CallFnOptions
type.
This is an advanced API.
Not available under no_function
.
§Example
use rhai::{Engine, Scope, Dynamic, CallFnOptions};
let engine = Engine::new();
let ast = engine.compile("
fn action(x) { this += x; } // function using 'this' pointer
fn decl(x) { let hello = x; } // declaring variables
")?;
let mut scope = Scope::new();
scope.push("foo", 42_i64);
// Binding the 'this' pointer
let mut value = 1_i64.into();
let options = CallFnOptions::new().bind_this_ptr(&mut value);
engine.call_fn_with_options(options, &mut scope, &ast, "action", ( 41_i64, ))?;
assert_eq!(value.as_int().unwrap(), 42);
// Do not rewind scope
let options = CallFnOptions::default().rewind_scope(false);
engine.call_fn_with_options(options, &mut scope, &ast, "decl", ( 42_i64, ))?;
assert_eq!(scope.get_value::<i64>("hello").unwrap(), 42);
Source§impl Engine
impl Engine
Sourcepub const fn allow_if_expression(&self) -> bool
pub const fn allow_if_expression(&self) -> bool
Is if
-expression allowed?
Default is true
.
Sourcepub fn set_allow_if_expression(&mut self, enable: bool) -> &mut Self
pub fn set_allow_if_expression(&mut self, enable: bool) -> &mut Self
Set whether if
-expression is allowed.
Sourcepub const fn allow_switch_expression(&self) -> bool
pub const fn allow_switch_expression(&self) -> bool
Is switch
expression allowed?
Default is true
.
Sourcepub fn set_allow_switch_expression(&mut self, enable: bool) -> &mut Self
pub fn set_allow_switch_expression(&mut self, enable: bool) -> &mut Self
Set whether switch
expression is allowed.
Sourcepub const fn allow_loop_expressions(&self) -> bool
pub const fn allow_loop_expressions(&self) -> bool
Are loop expressions allowed?
Default is true
.
Sourcepub fn set_allow_loop_expressions(&mut self, enable: bool) -> &mut Self
pub fn set_allow_loop_expressions(&mut self, enable: bool) -> &mut Self
Set whether loop expressions are allowed.
Sourcepub const fn allow_statement_expression(&self) -> bool
pub const fn allow_statement_expression(&self) -> bool
Is statement-expression allowed?
Default is true
.
Sourcepub fn set_allow_statement_expression(&mut self, enable: bool) -> &mut Self
pub fn set_allow_statement_expression(&mut self, enable: bool) -> &mut Self
Set whether statement-expression is allowed.
Sourcepub const fn allow_anonymous_fn(&self) -> bool
pub const fn allow_anonymous_fn(&self) -> bool
Is anonymous function allowed?
Default is true
.
Not available under no_function
.
Sourcepub fn set_allow_anonymous_fn(&mut self, enable: bool) -> &mut Self
pub fn set_allow_anonymous_fn(&mut self, enable: bool) -> &mut Self
Set whether anonymous function is allowed.
Not available under no_function
.
Sourcepub const fn allow_looping(&self) -> bool
pub const fn allow_looping(&self) -> bool
Is looping allowed?
Default is true
.
Sourcepub fn set_allow_looping(&mut self, enable: bool) -> &mut Self
pub fn set_allow_looping(&mut self, enable: bool) -> &mut Self
Set whether looping is allowed.
Sourcepub const fn allow_shadowing(&self) -> bool
pub const fn allow_shadowing(&self) -> bool
Is variables shadowing allowed?
Default is true
.
Sourcepub fn set_allow_shadowing(&mut self, enable: bool) -> &mut Self
pub fn set_allow_shadowing(&mut self, enable: bool) -> &mut Self
Set whether variables shadowing is allowed.
Sourcepub const fn strict_variables(&self) -> bool
pub const fn strict_variables(&self) -> bool
Is strict variables mode enabled?
Default is false
.
Sourcepub fn set_strict_variables(&mut self, enable: bool) -> &mut Self
pub fn set_strict_variables(&mut self, enable: bool) -> &mut Self
Set whether strict variables mode is enabled.
Sourcepub const fn fail_on_invalid_map_property(&self) -> bool
pub const fn fail_on_invalid_map_property(&self) -> bool
Raise error if an object map property does not exist?
Default is false
.
Not available under no_object
.
Sourcepub fn set_fail_on_invalid_map_property(&mut self, enable: bool) -> &mut Self
pub fn set_fail_on_invalid_map_property(&mut self, enable: bool) -> &mut Self
Set whether to raise error if an object map property does not exist.
Not available under no_object
.
Sourcepub const fn fast_operators(&self) -> bool
pub const fn fast_operators(&self) -> bool
Is fast operators mode enabled?
Default is false
.
Sourcepub fn set_fast_operators(&mut self, enable: bool) -> &mut Self
pub fn set_fast_operators(&mut self, enable: bool) -> &mut Self
Set whether fast operators mode is enabled.
Source§impl Engine
impl Engine
Sourcepub fn set_optimization_level(
&mut self,
optimization_level: OptimizationLevel,
) -> &mut Self
pub fn set_optimization_level( &mut self, optimization_level: OptimizationLevel, ) -> &mut Self
Sourcepub const fn optimization_level(&self) -> OptimizationLevel
pub const fn optimization_level(&self) -> OptimizationLevel
Sourcepub fn optimize_ast(
&self,
scope: &Scope<'_>,
ast: AST,
optimization_level: OptimizationLevel,
) -> AST
pub fn optimize_ast( &self, scope: &Scope<'_>, ast: AST, optimization_level: OptimizationLevel, ) -> AST
Optimize the AST
with constants defined in an external Scope.
An optimized copy of the AST
is returned while the original AST
is consumed.
Not available under no_optimize
.
Although optimization is performed by default during compilation, sometimes it is necessary
to re-optimize an AST
.
For example, when working with constants that are passed in via an external scope,
it will be more efficient to optimize the AST
once again to take advantage of the new constants.
With this method, it is no longer necessary to recompile a large script.
The script AST
can be compiled just once.
Before evaluation, constants are passed into the Engine
via an external scope
(i.e. with Scope::push_constant
).
Then, the AST
is cloned and the copy re-optimized before running.
Source§impl Engine
impl Engine
Sourcepub fn set_max_call_levels(&mut self, levels: usize) -> &mut Self
pub fn set_max_call_levels(&mut self, levels: usize) -> &mut Self
Set the maximum levels of function calls allowed for a script in order to avoid infinite recursion and stack overflows.
Not available under unchecked
or no_function
.
Sourcepub const fn max_call_levels(&self) -> usize
pub const fn max_call_levels(&self) -> usize
The maximum levels of function calls allowed for a script.
Not available under unchecked
or no_function
.
Sourcepub fn set_max_operations(&mut self, operations: u64) -> &mut Self
pub fn set_max_operations(&mut self, operations: u64) -> &mut Self
Set the maximum number of operations allowed for a script to run to avoid consuming too much resources (0 for unlimited).
Not available under unchecked
.
Sourcepub const fn max_operations(&self) -> u64
pub const fn max_operations(&self) -> u64
The maximum number of operations allowed for a script to run (0 for unlimited).
Not available under unchecked
.
Sourcepub fn set_max_variables(&mut self, variables: usize) -> &mut Self
pub fn set_max_variables(&mut self, variables: usize) -> &mut Self
Set the maximum number of variables allowed for a script at any instant.
Not available under unchecked
.
Sourcepub const fn max_variables(&self) -> usize
pub const fn max_variables(&self) -> usize
The maximum number of variables allowed for a script at any instant.
Not available under unchecked
.
Sourcepub fn set_max_functions(&mut self, functions: usize) -> &mut Self
pub fn set_max_functions(&mut self, functions: usize) -> &mut Self
Set the maximum number of scripted functions allowed for a script at any instant.
Not available under unchecked
or no_function
Sourcepub const fn max_functions(&self) -> usize
pub const fn max_functions(&self) -> usize
The maximum number of scripted functions allowed for a script at any instant.
Not available under unchecked
or no_function
Sourcepub fn set_max_modules(&mut self, modules: usize) -> &mut Self
pub fn set_max_modules(&mut self, modules: usize) -> &mut Self
Set the maximum number of imported modules allowed for a script.
Not available under unchecked
or no_module
.
Sourcepub const fn max_modules(&self) -> usize
pub const fn max_modules(&self) -> usize
The maximum number of imported modules allowed for a script.
Not available under unchecked
or no_module
.
Sourcepub fn set_max_expr_depths(
&mut self,
max_expr_depth: usize,
max_function_expr_depth: usize,
) -> &mut Self
pub fn set_max_expr_depths( &mut self, max_expr_depth: usize, max_function_expr_depth: usize, ) -> &mut Self
Set the depth limits for expressions (0 for unlimited).
Not available under unchecked
.
Sourcepub const fn max_expr_depth(&self) -> usize
pub const fn max_expr_depth(&self) -> usize
The depth limit for expressions (0 for unlimited).
Not available under unchecked
.
Sourcepub const fn max_function_expr_depth(&self) -> usize
pub const fn max_function_expr_depth(&self) -> usize
The depth limit for expressions in functions (0 for unlimited).
Not available under unchecked
or no_function
.
Sourcepub fn set_max_string_size(&mut self, max_len: usize) -> &mut Self
pub fn set_max_string_size(&mut self, max_len: usize) -> &mut Self
Set the maximum length, in bytes, of strings (0 for unlimited).
Not available under unchecked
.
Sourcepub const fn max_string_size(&self) -> usize
pub const fn max_string_size(&self) -> usize
The maximum length, in bytes, of strings (0 for unlimited).
Not available under unchecked
.
Sourcepub fn set_max_array_size(&mut self, max_size: usize) -> &mut Self
pub fn set_max_array_size(&mut self, max_size: usize) -> &mut Self
Set the maximum length of arrays (0 for unlimited).
Not available under unchecked
or no_index
.
Sourcepub const fn max_array_size(&self) -> usize
pub const fn max_array_size(&self) -> usize
The maximum length of arrays (0 for unlimited).
Not available under unchecked
or no_index
.
Sourcepub fn set_max_map_size(&mut self, max_size: usize) -> &mut Self
pub fn set_max_map_size(&mut self, max_size: usize) -> &mut Self
Set the maximum size of object maps (0 for unlimited).
Not available under unchecked
or no_object
.
Sourcepub const fn max_map_size(&self) -> usize
pub const fn max_map_size(&self) -> usize
The maximum size of object maps (0 for unlimited).
Not available under unchecked
or no_object
.
Source§impl Engine
impl Engine
Sourcepub fn on_var(
&mut self,
callback: impl Fn(&str, usize, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Option<Dynamic>, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
👎Deprecated: This API is NOT deprecated, but it is considered volatile and may change in the future.
pub fn on_var( &mut self, callback: impl Fn(&str, usize, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Option<Dynamic>, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
Provide a callback that will be invoked before each variable access.
§WARNING - Unstable API
This API is volatile and may change in the future.
§Callback Function Signature
Fn(name: &str, index: usize, context: EvalContext) -> Result<Option<Dynamic>, Box<EvalAltResult>>
where:
name
: name of the variable.index
: an offset from the bottom of the currentScope
that the variable is supposed to reside. Offsets start from 1, with 1 meaning the last variable in the currentScope
. Essentially the correct variable is at positionscope.len() - index
. Ifindex
is zero, then there is no pre-calculated offset position and a search through the currentScope
must be performed.context
: the current evaluation context.
§Return value
Ok(None)
: continue with normal variable access.Ok(Some(Dynamic))
: the variable’s value.
§Raising errors
Return Err(...)
if there is an error.
§Example
use rhai::Engine;
let mut engine = Engine::new();
// Register a variable resolver.
engine.on_var(|name, _, _| {
match name {
"MYSTIC_NUMBER" => Ok(Some(42_i64.into())),
_ => Ok(None)
}
});
engine.eval::<i64>("MYSTIC_NUMBER")?;
Sourcepub fn on_def_var(
&mut self,
callback: impl Fn(bool, VarDefInfo<'_>, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<bool, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
👎Deprecated: This API is NOT deprecated, but it is considered volatile and may change in the future.
pub fn on_def_var( &mut self, callback: impl Fn(bool, VarDefInfo<'_>, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<bool, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
Provide a callback that will be invoked before the definition of each variable .
§WARNING - Unstable API
This API is volatile and may change in the future.
§Callback Function Signature
Fn(is_runtime: bool, info: VarInfo, context: EvalContext) -> Result<bool, Box<EvalAltResult>>
where:
is_runtime
:true
if the variable definition event happens during runtime,false
if during compilation.info
: information on the variable.context
: the current evaluation context.
§Return value
Ok(true)
: continue with normal variable definition.Ok(false)
: deny the variable definition with an runtime error.
§Raising errors
Return Err(...)
if there is an error.
§Example
use rhai::Engine;
let mut engine = Engine::new();
// Register a variable definition filter.
engine.on_def_var(|_, info, _| {
// Disallow defining MYSTIC_NUMBER as a constant
if info.name() == "MYSTIC_NUMBER" && info.is_const() {
Ok(false)
} else {
Ok(true)
}
});
// The following runs fine:
engine.eval::<i64>("let MYSTIC_NUMBER = 42;")?;
// The following will cause an error:
engine.eval::<i64>("const MYSTIC_NUMBER = 42;")?;
Sourcepub fn on_parse_token(
&mut self,
callback: impl Fn(Token, Position, &TokenizeState) -> Token + SendSync + 'static,
) -> &mut Self
👎Deprecated: This API is NOT deprecated, but it is considered volatile and may change in the future.
pub fn on_parse_token( &mut self, callback: impl Fn(Token, Position, &TokenizeState) -> Token + SendSync + 'static, ) -> &mut Self
(internals) Register a callback that will be invoked during parsing to remap certain tokens.
Exported under the internals
feature only.
§WARNING - Unstable API
This API is volatile and may change in the future.
§Callback Function Signature
Fn(token: Token, pos: Position, state: &TokenizeState) -> Token
where:
§Raising errors
It is possible to raise a parsing error by returning
Token::LexError
as the mapped token.
§Example
use rhai::{Engine, Token};
let mut engine = Engine::new();
// Register a token mapper.
engine.on_parse_token(|token, _, _| {
match token {
// Convert all integer literals to strings
Token::IntegerConstant(n) => Token::StringConstant(Box::new(n.to_string().into())),
// Convert 'begin' .. 'end' to '{' .. '}'
Token::Identifier(s) if &*s == "begin" => Token::LeftBrace,
Token::Identifier(s) if &*s == "end" => Token::RightBrace,
// Pass through all other tokens unchanged
_ => token
}
});
assert_eq!(engine.eval::<String>("42")?, "42");
assert_eq!(engine.eval::<bool>("true")?, true);
assert_eq!(engine.eval::<String>("let x = 42; begin let x = 0; end; x")?, "42");
Sourcepub fn on_progress(
&mut self,
callback: impl Fn(u64) -> Option<Dynamic> + SendSync + 'static,
) -> &mut Self
pub fn on_progress( &mut self, callback: impl Fn(u64) -> Option<Dynamic> + SendSync + 'static, ) -> &mut Self
Register a callback for script evaluation progress.
Not available under unchecked
.
§Callback Function Signature
Fn(counter: u64) -> Option<Dynamic>
§Return value
None
: continue running the script.Some(Dynamic)
: terminate the script with the specified exception value.
§Example
use rhai::Engine;
let result = Arc::new(RwLock::new(0_u64));
let logger = result.clone();
let mut engine = Engine::new();
engine.on_progress(move |ops| {
if ops > 1000 {
Some("Over 1,000 operations!".into())
} else if ops % 123 == 0 {
*logger.write().unwrap() = ops;
None
} else {
None
}
});
engine.run("for x in 0..5000 { print(x); }")
.expect_err("should error");
assert_eq!(*result.read().unwrap(), 984);
Sourcepub fn on_print(
&mut self,
callback: impl Fn(&str) + SendSync + 'static,
) -> &mut Self
pub fn on_print( &mut self, callback: impl Fn(&str) + SendSync + 'static, ) -> &mut Self
Override default action of print
(print to stdout using println!
)
§Example
use rhai::Engine;
let result = Arc::new(RwLock::new(String::new()));
let mut engine = Engine::new();
// Override action of 'print' function
let logger = result.clone();
engine.on_print(move |s| logger.write().unwrap().push_str(s));
engine.run("print(40 + 2);")?;
assert_eq!(*result.read().unwrap(), "42");
Sourcepub fn on_debug(
&mut self,
callback: impl Fn(&str, Option<&str>, Position) + SendSync + 'static,
) -> &mut Self
pub fn on_debug( &mut self, callback: impl Fn(&str, Option<&str>, Position) + SendSync + 'static, ) -> &mut Self
Override default action of debug
(print to stdout using println!
)
§Callback Function Signature
The callback function signature passed takes the following form:
Fn(text: &str, source: Option<&str>, pos: Position)
where:
text
: the text to displaysource
: current source, if anypos
: location of thedebug
call
§Example
use rhai::Engine;
let result = Arc::new(RwLock::new(String::new()));
let mut engine = Engine::new();
// Override action of 'print' function
let logger = result.clone();
engine.on_debug(move |s, src, pos| logger.write().unwrap().push_str(
&format!("{} @ {:?} > {}", src.unwrap_or("unknown"), pos, s)
));
let mut ast = engine.compile(r#"let x = "hello"; debug(x);"#)?;
ast.set_source("world");
engine.run_ast(&ast)?;
#[cfg(not(feature = "no_position"))]
assert_eq!(*result.read().unwrap(), r#"world @ 1:18 > "hello""#);
#[cfg(feature = "no_position")]
assert_eq!(*result.read().unwrap(), r#"world @ none > "hello""#);
Sourcepub fn on_invalid_array_index(
&mut self,
callback: impl for<'a> Fn(&'a mut Array, INT, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Target<'a>, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
pub fn on_invalid_array_index( &mut self, callback: impl for<'a> Fn(&'a mut Array, INT, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Target<'a>, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
(internals) Register a callback for access to Map
properties that do not exist.
Exported under the internals
feature only.
Not available under no_index
.
§WARNING - Unstable API
This API is volatile and may change in the future.
§Callback Function Signature
Fn(array: &mut Array, index: INT) -> Result<Target, Box<EvalAltResult>>
where:
array
: mutable reference to theArray
instance.index
: numeric index of the array access.
§Return value
Ok(Target)
:Target
of the indexing access.
§Raising errors
Return Err(...)
if there is an error, usually
EvalAltResult::ErrorPropertyNotFound
.
§Example
let mut engine = Engine::new();
engine.on_invalid_array_index(|arr, index, _| match index
{
-100 => {
// The array can be modified in place
arr.push((42_i64).into());
// Return a mutable reference to an element
let value_ref = arr.last_mut().unwrap();
value_ref.try_into()
}
100 => {
let value = Dynamic::from(100_i64);
// Return a temporary value (not a reference)
Ok(value.into())
}
// Return the standard out-of-bounds error
_ => Err(EvalAltResult::ErrorArrayBounds(
arr.len(), index, Position::NONE
).into()),
});
let r = engine.eval::<i64>("
let a = [1, 2, 3];
a[-100] += 1;
a[3] + a[100]
")?;
assert_eq!(r, 143);
Sourcepub fn on_map_missing_property(
&mut self,
callback: impl for<'a> Fn(&'a mut Map, &str, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Target<'a>, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
pub fn on_map_missing_property( &mut self, callback: impl for<'a> Fn(&'a mut Map, &str, EvalContext<'_, '_, '_, '_, '_, '_>) -> Result<Target<'a>, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
(internals) Register a callback for access to Map
properties that do not exist.
Exported under the internals
feature only.
Not available under no_object
.
§WARNING - Unstable API
This API is volatile and may change in the future.
§Callback Function Signature
Fn(map: &mut Map, prop: &str) -> Result<Target, Box<EvalAltResult>>
where:
map
: mutable reference to theMap
instance.prop
: name of the property that does not exist.
§Return value
Ok(Target)
:Target
of the property access.
§Raising errors
Return Err(...)
if there is an error, usually EvalAltResult::ErrorPropertyNotFound
.
§Example
let mut engine = Engine::new();
engine.on_map_missing_property(|map, prop, _| match prop
{
"x" => {
// The object-map can be modified in place
map.insert("y".into(), (42_i64).into());
// Return a mutable reference to an element
let value_ref = map.get_mut("y").unwrap();
value_ref.try_into()
}
"z" => {
// Return a temporary value (not a reference)
let value = Dynamic::from(100_i64);
Ok(value.into())
}
// Return the standard property-not-found error
_ => Err(EvalAltResult::ErrorPropertyNotFound(
prop.to_string(), Position::NONE
).into()),
});
let r = engine.eval::<i64>("
let obj = #{ a:1, b:2 };
obj.x += 1;
obj.y + obj.z
")?;
assert_eq!(r, 143);
Sourcepub fn register_debugger(
&mut self,
init: impl Fn(&Self, Debugger) -> Debugger + SendSync + 'static,
callback: impl Fn(EvalContext<'_, '_, '_, '_, '_, '_>, DebuggerEvent<'_>, ASTNode<'_>, Option<&str>, Position) -> Result<DebuggerCommand, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
👎Deprecated: This API is NOT deprecated, but it is considered volatile and may change in the future.
pub fn register_debugger( &mut self, init: impl Fn(&Self, Debugger) -> Debugger + SendSync + 'static, callback: impl Fn(EvalContext<'_, '_, '_, '_, '_, '_>, DebuggerEvent<'_>, ASTNode<'_>, Option<&str>, Position) -> Result<DebuggerCommand, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
(debugging) Register a callback for debugging.
Exported under the debugging
feature only.
§WARNING - Unstable API
This API is volatile and may change in the future.
Source§impl Engine
impl Engine
Sourcepub fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str
pub fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str
Pretty-print a type name.
If a type is registered via register_type_with_name
,
the type name provided for the registration will be used.
Sourcepub fn compact_script(
&self,
script: impl AsRef<str>,
) -> Result<String, ParseError>
pub fn compact_script( &self, script: impl AsRef<str>, ) -> Result<String, ParseError>
Compact a script to eliminate insignificant whitespaces and comments.
This is useful to prepare a script for further compressing.
The output script is semantically identical to the input script, except smaller in size.
Unlike other uglifiers and minifiers, this method does not rename variables nor perform any optimization on the input script.
Source§impl Engine
impl Engine
Sourcepub fn register_custom_syntax<S: AsRef<str> + Into<Identifier>>(
&mut self,
symbols: impl AsRef<[S]>,
scope_may_be_changed: bool,
func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>]) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static,
) -> Result<&mut Self, ParseError>
pub fn register_custom_syntax<S: AsRef<str> + Into<Identifier>>( &mut self, symbols: impl AsRef<[S]>, scope_may_be_changed: bool, func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>]) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static, ) -> Result<&mut Self, ParseError>
Register a custom syntax with the Engine
.
Not available under no_custom_syntax
.
symbols
holds a slice of strings that define the custom syntax.scope_may_be_changed
specifies variables may be added/removed by this custom syntax.func
is the implementation function.
§Note on symbols
- Whitespaces around symbols are stripped.
- Symbols that are all-whitespace or empty are ignored.
- If
symbols
does not contain at least one valid token, then the custom syntax registration is simply ignored.
§Note on scope_may_be_changed
If scope_may_be_changed
is true
, then size of the current Scope
may be modified by this custom syntax.
Adding new variables and/or removing variables count.
Simply modifying the values of existing variables does NOT count, as the size of the
current Scope
is unchanged, so false
should be passed.
Replacing one variable with another (i.e. adding a new variable and removing one variable at
the same time so that the total size of the Scope
is unchanged) also
does NOT count, so false
should be passed.
Sourcepub fn register_custom_syntax_with_state_raw(
&mut self,
key: impl Into<Identifier>,
parse: impl Fn(&[ImmutableString], &str, &mut Dynamic) -> Result<Option<ImmutableString>, ParseError> + SendSync + 'static,
scope_may_be_changed: bool,
func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>], &Dynamic) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
pub fn register_custom_syntax_with_state_raw( &mut self, key: impl Into<Identifier>, parse: impl Fn(&[ImmutableString], &str, &mut Dynamic) -> Result<Option<ImmutableString>, ParseError> + SendSync + 'static, scope_may_be_changed: bool, func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>], &Dynamic) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
Register a custom syntax with the Engine
with custom user-defined state.
Not available under no_custom_syntax
.
§WARNING - Low Level API
This function is very low level.
scope_may_be_changed
specifies variables have been added/removed by this custom syntax.parse
is the parsing function.func
is the implementation function.
All custom keywords used as symbols must be manually registered via Engine::register_custom_operator
.
Otherwise, they won’t be recognized.
§Parsing Function Signature
The parsing function has the following signature:
Fn(symbols: &[ImmutableString], look_ahead: &str, state: &mut Dynamic) -> Result<Option<ImmutableString>, ParseError>
where:
symbols
: a slice of symbols that have been parsed so far, possibly containing$expr$
and/or$block$
;$ident$
and other literal markers are replaced by the actual textlook_ahead
: a string slice containing the next symbol that is about to be readstate
: aDynamic
value that contains a user-defined state
§Return value
Ok(None)
: parsing complete and there are no more symbols to match.Ok(Some(symbol))
: the next symbol to match, which can also be$expr$
,$ident$
or$block$
.Err(ParseError)
: error that is reflected back to theEngine
, normallyParseError(ParseErrorType::BadInput(LexError::ImproperSymbol(message)), Position::NONE)
to indicate a syntax error, but it can be anyParseError
.
Source§impl Engine
impl Engine
Sourcepub fn build_type<T: CustomType>(&mut self) -> &mut Self
pub fn build_type<T: CustomType>(&mut self) -> &mut Self
Build the API of a custom type for use with the Engine
.
The custom type must implement CustomType
.
Source§impl Engine
impl Engine
Sourcepub fn definitions(&self) -> Definitions<'_>
pub fn definitions(&self) -> Definitions<'_>
(metadata, internals) Return Definitions
that can be used to generate definition files
for the Engine
.
Exported under the internals
and metadata
feature only.
§Example
let engine = Engine::new();
engine
.definitions()
.write_to_dir(".rhai/definitions")?;
Sourcepub fn definitions_with_scope<'e>(
&'e self,
scope: &'e Scope<'e>,
) -> Definitions<'e>
pub fn definitions_with_scope<'e>( &'e self, scope: &'e Scope<'e>, ) -> Definitions<'e>
(metadata, internals) Return Definitions
that can be used to generate definition files
for the Engine
and the given Scope
.
Exported under the internals
and metadata
feature only.
§Example
let engine = Engine::new();
let scope = Scope::new();
engine
.definitions_with_scope(&scope)
.write_to_dir(".rhai/definitions")?;
Source§impl Engine
impl Engine
Sourcepub fn consume_file(&self, path: PathBuf) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run_file
instead
pub fn consume_file(&self, path: PathBuf) -> Result<(), Box<EvalAltResult>>
run_file
insteadEvaluate a file, but throw away the result and only return error (if any). Useful for when you don’t need the result, but still need to keep track of possible errors.
Not available under no_std
or WASM
.
§Deprecated
This method is deprecated.
Use run_file
instead.
This method will be removed in the next major version.
Sourcepub fn consume_file_with_scope(
&self,
scope: &mut Scope<'_>,
path: PathBuf,
) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run_file_with_scope
instead
pub fn consume_file_with_scope( &self, scope: &mut Scope<'_>, path: PathBuf, ) -> Result<(), Box<EvalAltResult>>
run_file_with_scope
insteadEvaluate a file with own scope, but throw away the result and only return error (if any). Useful for when you don’t need the result, but still need to keep track of possible errors.
Not available under no_std
or WASM
.
§Deprecated
This method is deprecated.
Use run_file_with_scope
instead.
This method will be removed in the next major version.
Sourcepub fn consume(&self, script: &str) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run
instead
pub fn consume(&self, script: &str) -> Result<(), Box<EvalAltResult>>
run
insteadSourcepub fn consume_with_scope(
&self,
scope: &mut Scope<'_>,
script: &str,
) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run_with_scope
instead
pub fn consume_with_scope( &self, scope: &mut Scope<'_>, script: &str, ) -> Result<(), Box<EvalAltResult>>
run_with_scope
insteadEvaluate a string with own scope, but throw away the result and only return error (if any). Useful for when you don’t need the result, but still need to keep track of possible errors.
§Deprecated
This method is deprecated.
Use run_with_scope
instead.
This method will be removed in the next major version.
Sourcepub fn consume_ast(&self, ast: &AST) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run_ast
instead
pub fn consume_ast(&self, ast: &AST) -> Result<(), Box<EvalAltResult>>
run_ast
insteadSourcepub fn consume_ast_with_scope(
&self,
scope: &mut Scope<'_>,
ast: &AST,
) -> Result<(), Box<EvalAltResult>>
👎Deprecated since 1.1.0: use run_ast_with_scope
instead
pub fn consume_ast_with_scope( &self, scope: &mut Scope<'_>, ast: &AST, ) -> Result<(), Box<EvalAltResult>>
run_ast_with_scope
insteadEvaluate an AST
with own scope, but throw away the result and only return error (if any).
Useful for when you don’t need the result, but still need to keep track of possible errors.
§Deprecated
This method is deprecated.
Use run_ast_with_scope
instead.
This method will be removed in the next major version.
Sourcepub fn call_fn_dynamic(
&self,
scope: &mut Scope<'_>,
ast: &AST,
eval_ast: bool,
name: impl AsRef<str>,
this_ptr: Option<&mut Dynamic>,
arg_values: impl AsMut<[Dynamic]>,
) -> Result<Dynamic, Box<EvalAltResult>>
👎Deprecated since 1.1.0: use call_fn_with_options
instead
pub fn call_fn_dynamic( &self, scope: &mut Scope<'_>, ast: &AST, eval_ast: bool, name: impl AsRef<str>, this_ptr: Option<&mut Dynamic>, arg_values: impl AsMut<[Dynamic]>, ) -> Result<Dynamic, Box<EvalAltResult>>
call_fn_with_options
insteadCall a script function defined in an AST
with multiple Dynamic
arguments
and optionally a value for binding to the this
pointer.
Not available under no_function
.
There is an option to evaluate the AST
to load necessary modules before calling the function.
§Deprecated
This method is deprecated.
Use call_fn_with_options
instead.
This method will be removed in the next major version.
Sourcepub fn call_fn_raw(
&self,
scope: &mut Scope<'_>,
ast: &AST,
eval_ast: bool,
rewind_scope: bool,
name: impl AsRef<str>,
this_ptr: Option<&mut Dynamic>,
arg_values: impl AsMut<[Dynamic]>,
) -> Result<Dynamic, Box<EvalAltResult>>
👎Deprecated since 1.12.0: use call_fn_with_options
instead
pub fn call_fn_raw( &self, scope: &mut Scope<'_>, ast: &AST, eval_ast: bool, rewind_scope: bool, name: impl AsRef<str>, this_ptr: Option<&mut Dynamic>, arg_values: impl AsMut<[Dynamic]>, ) -> Result<Dynamic, Box<EvalAltResult>>
call_fn_with_options
insteadCall a script function defined in an AST
with multiple Dynamic
arguments.
Not available under no_function
.
§Deprecated
This method is deprecated.
Use call_fn_with_options
instead.
This method will be removed in the next major version.
Sourcepub fn register_result_fn<A: 'static, const N: usize, const X: bool, R: Variant + Clone>(
&mut self,
name: impl AsRef<str> + Into<Identifier>,
func: impl RhaiNativeFunc<A, N, X, R, true> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.9.1: use register_fn
instead
pub fn register_result_fn<A: 'static, const N: usize, const X: bool, R: Variant + Clone>( &mut self, name: impl AsRef<str> + Into<Identifier>, func: impl RhaiNativeFunc<A, N, X, R, true> + SendSync + 'static, ) -> &mut Self
register_fn
insteadRegister a custom fallible function with the Engine
.
§Deprecated
This method is deprecated.
Use register_fn
instead.
This method will be removed in the next major version.
Sourcepub fn register_get_result<T: Variant + Clone, const X: bool, R: Variant + Clone>(
&mut self,
name: impl AsRef<str>,
get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X, R, true> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.9.1: use register_get
instead
pub fn register_get_result<T: Variant + Clone, const X: bool, R: Variant + Clone>( &mut self, name: impl AsRef<str>, get_fn: impl RhaiNativeFunc<(Mut<T>,), 1, X, R, true> + SendSync + 'static, ) -> &mut Self
register_get
insteadRegister a getter function for a member of a registered type with the Engine
.
The function signature must start with &mut self
and not &self
.
Not available under no_object
.
§Deprecated
This method is deprecated.
Use register_get
instead.
This method will be removed in the next major version.
Sourcepub fn register_set_result<T: Variant + Clone, V: Variant + Clone, const X: bool>(
&mut self,
name: impl AsRef<str>,
set_fn: impl RhaiNativeFunc<(Mut<T>, V), 2, X, (), true> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.9.1: use register_set
instead
pub fn register_set_result<T: Variant + Clone, V: Variant + Clone, const X: bool>( &mut self, name: impl AsRef<str>, set_fn: impl RhaiNativeFunc<(Mut<T>, V), 2, X, (), true> + SendSync + 'static, ) -> &mut Self
register_set
insteadRegister a setter function for a member of a registered type with the Engine
.
Not available under no_object
.
§Deprecated
This method is deprecated.
Use register_set
instead.
This method will be removed in the next major version.
Sourcepub fn register_indexer_get_result<T: Variant + Clone, IDX: Variant + Clone, R: Variant + Clone, const X: bool>(
&mut self,
get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X, R, true> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.9.1: use register_indexer_get
instead
pub fn register_indexer_get_result<T: Variant + Clone, IDX: Variant + Clone, R: Variant + Clone, const X: bool>( &mut self, get_fn: impl RhaiNativeFunc<(Mut<T>, IDX), 2, X, R, true> + SendSync + 'static, ) -> &mut Self
register_indexer_get
insteadRegister an index getter for a custom type with the Engine
.
The function signature must start with &mut self
and not &self
.
Not available under both no_index
and no_object
.
§Deprecated
This method is deprecated.
Use register_indexer_get
instead.
This method will be removed in the next major version.
Sourcepub fn register_indexer_set_result<T: Variant + Clone, IDX: Variant + Clone, R: Variant + Clone, const X: bool>(
&mut self,
set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X, (), true> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.9.1: use register_indexer_set
instead
pub fn register_indexer_set_result<T: Variant + Clone, IDX: Variant + Clone, R: Variant + Clone, const X: bool>( &mut self, set_fn: impl RhaiNativeFunc<(Mut<T>, IDX, R), 3, X, (), true> + SendSync + 'static, ) -> &mut Self
register_indexer_set
insteadRegister an index setter for a custom type with the Engine
.
Not available under both no_index
and no_object
.
§Deprecated
This method is deprecated.
Use register_indexer_set
instead.
This method will be removed in the next major version.
Sourcepub fn register_custom_syntax_raw(
&mut self,
key: impl Into<Identifier>,
parse: impl Fn(&[ImmutableString], &str) -> Result<Option<ImmutableString>, ParseError> + SendSync + 'static,
scope_may_be_changed: bool,
func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>]) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static,
) -> &mut Self
👎Deprecated since 1.11.0: use register_custom_syntax_with_state_raw
instead
pub fn register_custom_syntax_raw( &mut self, key: impl Into<Identifier>, parse: impl Fn(&[ImmutableString], &str) -> Result<Option<ImmutableString>, ParseError> + SendSync + 'static, scope_may_be_changed: bool, func: impl Fn(&mut EvalContext<'_, '_, '_, '_, '_, '_>, &[Expression<'_>]) -> Result<Dynamic, Box<EvalAltResult>> + SendSync + 'static, ) -> &mut Self
register_custom_syntax_with_state_raw
insteadRegister a custom syntax with the Engine
.
Not available under no_custom_syntax
.
§Deprecated
This method is deprecated.
Use register_custom_syntax_with_state_raw
instead.
This method will be removed in the next major version.
Sourcepub fn eval_statements_raw(
&self,
global: &mut GlobalRuntimeState,
caches: &mut Caches,
scope: &mut Scope<'_>,
statements: &[Stmt],
) -> Result<Dynamic, Box<EvalAltResult>>
👎Deprecated since 1.12.0
pub fn eval_statements_raw( &self, global: &mut GlobalRuntimeState, caches: &mut Caches, scope: &mut Scope<'_>, statements: &[Stmt], ) -> Result<Dynamic, Box<EvalAltResult>>
(internals) Evaluate a list of statements with no this
pointer.
Exported under the internals
feature only.
§Deprecated
This method is deprecated. It will be removed in the next major version.
Source§impl Engine
impl Engine
Sourcepub fn set_max_strings_interned(&mut self, max: usize) -> &mut Self
pub fn set_max_strings_interned(&mut self, max: usize) -> &mut Self
Set the maximum number of strings to be interned.
Sourcepub fn max_strings_interned(&self) -> usize
pub fn max_strings_interned(&self) -> usize
The maximum number of strings to be interned.
Sourcepub fn module_resolver(&self) -> &dyn ModuleResolver
pub fn module_resolver(&self) -> &dyn ModuleResolver
The module resolution service used by the Engine
.
Not available under no_module
.
Sourcepub fn set_module_resolver(
&mut self,
resolver: impl ModuleResolver + 'static,
) -> &mut Self
pub fn set_module_resolver( &mut self, resolver: impl ModuleResolver + 'static, ) -> &mut Self
Set the module resolution service used by the Engine
.
Not available under no_module
.
Sourcepub fn disable_symbol(&mut self, symbol: impl Into<Identifier>) -> &mut Self
pub fn disable_symbol(&mut self, symbol: impl Into<Identifier>) -> &mut Self
Disable a particular keyword or operator in the language.
§Examples
The following will raise an error during parsing because the if
keyword is disabled and is
recognized as a reserved symbol!
use rhai::Engine;
let mut engine = Engine::new();
engine.disable_symbol("if"); // disable the 'if' keyword
engine.compile("let x = if true { 42 } else { 0 };")?;
// ^ 'if' is rejected as a reserved symbol
The following will raise an error during parsing because the +=
operator is disabled.
use rhai::Engine;
let mut engine = Engine::new();
engine.disable_symbol("+="); // disable the '+=' operator
engine.compile("let x = 42; x += 1;")?;
// ^ unknown operator
Sourcepub fn is_symbol_disabled(&self, symbol: &str) -> bool
pub fn is_symbol_disabled(&self, symbol: &str) -> bool
Is a particular keyword or operator disabled?
§Examples
use rhai::Engine;
let mut engine = Engine::new();
engine.disable_symbol("if"); // disable the 'if' keyword
assert!(engine.is_symbol_disabled("if"));
Sourcepub fn register_custom_operator(
&mut self,
keyword: impl AsRef<str>,
precedence: u8,
) -> Result<&mut Self, String>
pub fn register_custom_operator( &mut self, keyword: impl AsRef<str>, precedence: u8, ) -> Result<&mut Self, String>
Register a custom operator with a precedence into the language.
Not available under no_custom_syntax
.
The operator can be a valid identifier, a reserved symbol, a disabled operator or a disabled keyword.
The precedence cannot be zero.
§Example
use rhai::Engine;
let mut engine = Engine::new();
// Register a custom operator called '#' and give it
// a precedence of 160 (i.e. between +|- and *|/).
engine.register_custom_operator("#", 160).expect("should succeed");
// Register a binary function named '#'
engine.register_fn("#", |x: i64, y: i64| (x * y) - (x + y));
assert_eq!(
engine.eval_expression::<i64>("1 + 2 * 3 # 4 - 5 / 6")?,
15
);
Sourcepub const fn default_tag(&self) -> &Dynamic
pub const fn default_tag(&self) -> &Dynamic
Get the default value of the custom state for each evaluation run.
Sourcepub fn default_tag_mut(&mut self) -> &mut Dynamic
pub fn default_tag_mut(&mut self) -> &mut Dynamic
Get a mutable reference to the default value of the custom state for each evaluation run.
Sourcepub fn set_default_tag(&mut self, value: impl Into<Dynamic>) -> &mut Self
pub fn set_default_tag(&mut self, value: impl Into<Dynamic>) -> &mut Self
Set the default value of the custom state for each evaluation run.
Source§impl Engine
impl Engine
Sourcepub const fn new_raw() -> Self
pub const fn new_raw() -> Self
Create a new Engine
with minimal built-in functions.
It returns a copy of Engine::RAW
.
This is useful for creating a custom scripting engine with only the functions you need.
Use register_global_module
to add packages of functions.
Sourcepub fn get_interned_string(
&self,
string: impl AsRef<str> + Into<ImmutableString>,
) -> ImmutableString
pub fn get_interned_string( &self, string: impl AsRef<str> + Into<ImmutableString>, ) -> ImmutableString
Get an interned string.
Engine
keeps a cache of ImmutableString
instances and tries to avoid new allocations
and save memory when an existing instance is found.
It is usually a good idea to intern strings if they are used frequently.
Sourcepub fn const_empty_string(&self) -> ImmutableString
pub fn const_empty_string(&self) -> ImmutableString
Get an empty ImmutableString
which refers to a shared instance.
Source§impl Engine
impl Engine
Sourcepub fn ensure_data_size_within_limits(
&self,
value: &Dynamic,
) -> Result<(), Box<EvalAltResult>>
pub fn ensure_data_size_within_limits( &self, value: &Dynamic, ) -> Result<(), Box<EvalAltResult>>
Raise an error if the size of a Dynamic
is out of limits (if any).
Not available under unchecked
.
Source§impl Engine
impl Engine
Sourcepub fn new_global_runtime_state(&self) -> GlobalRuntimeState
pub fn new_global_runtime_state(&self) -> GlobalRuntimeState
(internals) Create a new GlobalRuntimeState
based on an Engine
.
Exported under the internals
feature only.
Source§impl Engine
impl Engine
Sourcepub fn gen_fn_metadata_with_ast_to_json(
&self,
ast: &AST,
include_standard_packages: bool,
) -> Result<String>
pub fn gen_fn_metadata_with_ast_to_json( &self, ast: &AST, include_standard_packages: bool, ) -> Result<String>
(metadata) Generate a list of all functions (including those defined in an
AST
) in JSON format.
Exported under the metadata
feature only.
Functions from the following sources are included:
- Functions defined in an
AST
- Functions registered into the global namespace
- Functions in static modules
- Functions in registered global packages
- Functions in standard packages (optional)
Sourcepub fn gen_fn_metadata_to_json(
&self,
include_standard_packages: bool,
) -> Result<String>
pub fn gen_fn_metadata_to_json( &self, include_standard_packages: bool, ) -> Result<String>
Generate a list of all functions in JSON format.
Exported under the metadata
feature only.
Functions from the following sources are included:
- Functions registered into the global namespace
- Functions in static modules
- Functions in registered global packages
- Functions in standard packages (optional)
Source§impl Engine
impl Engine
Sourcepub fn lex<'a>(
&'a self,
inputs: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a)>,
) -> (TokenIterator<'a>, TokenizerControl)
pub fn lex<'a>( &'a self, inputs: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a)>, ) -> (TokenIterator<'a>, TokenizerControl)
(internals) Tokenize an input text stream.
Exported under the internals
feature only.
Sourcepub fn lex_with_map<'a>(
&'a self,
inputs: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a)>,
token_mapper: &'a dyn Fn(Token, Position, &TokenizeState) -> Token,
) -> (TokenIterator<'a>, TokenizerControl)
pub fn lex_with_map<'a>( &'a self, inputs: impl IntoIterator<Item = &'a (impl AsRef<str> + 'a)>, token_mapper: &'a dyn Fn(Token, Position, &TokenizeState) -> Token, ) -> (TokenIterator<'a>, TokenizerControl)
(internals) Tokenize an input text stream with a mapping function.
Exported under the internals
feature only.