pub struct Module { /* private fields */ }
Expand description
A module which may contain variables, sub-modules, external Rust functions, and/or script-defined functions.
Implementations
sourceimpl Module
impl Module
sourcepub fn set_id(&mut self, id: impl Into<Identifier>) -> &mut Self
pub fn set_id(&mut self, id: impl Into<Identifier>) -> &mut Self
sourcepub fn set_custom_type<T>(&mut self, name: &str)
pub fn set_custom_type<T>(&mut self, name: &str)
Map a custom type to a friendly display name.
sourcepub fn set_custom_type_raw(
&mut self,
type_name: impl Into<Identifier>,
name: impl Into<Identifier>
)
pub fn set_custom_type_raw(
&mut self,
type_name: impl Into<Identifier>,
name: impl Into<Identifier>
)
Map a custom type to a friendly display name.
sourcepub fn get_custom_type(&self, key: &str) -> Option<&str>
pub fn get_custom_type(&self, key: &str) -> Option<&str>
Get the display name of a registered custom type.
sourcepub const fn is_indexed(&self) -> bool
pub const fn is_indexed(&self) -> bool
Is the Module
indexed?
A module must be indexed before it can be used in an import
statement.
Example
let mut module = Module::new();
assert!(module.is_indexed());
module.set_native_fn("foo", |x: &mut i64, y: i64| { *x = y; Ok(()) });
assert!(!module.is_indexed());
module.build_index();
assert!(module.is_indexed());
sourcepub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_
pub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_
(metadata) Generate signatures for all the non-private functions in the Module
.
Exported under the metadata
feature only.
sourcepub fn contains_var(&self, name: &str) -> bool
pub fn contains_var(&self, name: &str) -> bool
sourcepub fn set_var(
&mut self,
name: impl Into<Identifier>,
value: impl Variant + Clone
) -> &mut Self
pub fn set_var(
&mut self,
name: impl Into<Identifier>,
value: impl Variant + Clone
) -> &mut Self
sourcepub fn set_script_fn(&mut self, fn_def: impl Into<Shared<ScriptFnDef>>) -> u64
pub fn set_script_fn(&mut self, fn_def: impl Into<Shared<ScriptFnDef>>) -> u64
Set a script-defined function into the Module
.
If there is an existing function of the same name and number of arguments, it is replaced.
sourcepub fn get_script_fn(
&self,
name: impl AsRef<str>,
num_params: usize
) -> Option<&Shared<ScriptFnDef>>
pub fn get_script_fn(
&self,
name: impl AsRef<str>,
num_params: usize
) -> Option<&Shared<ScriptFnDef>>
Get a shared reference to the script-defined function in the Module
based on name
and number of parameters.
sourcepub fn contains_sub_module(&self, name: &str) -> bool
pub fn contains_sub_module(&self, name: &str) -> bool
sourcepub fn get_sub_module(&self, name: &str) -> Option<&Module>
pub fn get_sub_module(&self, name: &str) -> Option<&Module>
sourcepub fn set_sub_module(
&mut self,
name: impl Into<Identifier>,
sub_module: impl Into<Shared<Module>>
) -> &mut Self
pub fn set_sub_module(
&mut self,
name: impl Into<Identifier>,
sub_module: impl Into<Shared<Module>>
) -> &mut Self
sourcepub fn contains_fn(&self, hash_fn: u64) -> bool
pub fn contains_fn(&self, hash_fn: u64) -> bool
Does the particular Rust function exist in the Module
?
The u64
hash is returned by the set_native_fn
call.
Example
let mut module = Module::new();
let hash = module.set_native_fn("calc", || Ok(42_i64));
assert!(module.contains_fn(hash));
sourcepub fn update_fn_metadata<S: AsRef<str>>(
&mut self,
hash_fn: u64,
arg_names: impl AsRef<[S]>
) -> &mut Self
pub fn update_fn_metadata<S: AsRef<str>>(
&mut self,
hash_fn: u64,
arg_names: impl AsRef<[S]>
) -> &mut Self
(metadata) Update the metadata (parameter names/types and return type) of a registered function.
Exported under the metadata
feature only.
The u64
hash is returned by the set_native_fn
call.
Parameter Names and Types
Each parameter name/type pair should be a single string of the format: var_name: type
.
Return Type
The last entry in the list should be the return type of the function. In other words, the number of entries should be one larger than the number of parameters.
sourcepub fn update_fn_metadata_with_comments<A: AsRef<str>, C: AsRef<str>>(
&mut self,
hash_fn: u64,
arg_names: impl AsRef<[A]>,
comments: impl AsRef<[C]>
) -> &mut Self
pub fn update_fn_metadata_with_comments<A: AsRef<str>, C: AsRef<str>>(
&mut self,
hash_fn: u64,
arg_names: impl AsRef<[A]>,
comments: impl AsRef<[C]>
) -> &mut Self
(metadata) Update the metadata (parameter names/types, return type and doc-comments) of a registered function.
Exported under the metadata
feature only.
The u64
hash is returned by the set_native_fn
call.
Parameter Names and Types
Each parameter name/type pair should be a single string of the format: var_name: type
.
Return Type
The last entry in the list should be the return type of the function. In other words, the number of entries should be one larger than the number of parameters.
Comments
Block doc-comments should be kept in a single line.
Line doc-comments should be kept in one string slice per line without the termination line-break.
Leading white-spaces should be stripped, and each string slice always starts with the corresponding
doc-comment leader: ///
or /**
.
sourcepub fn update_fn_namespace(
&mut self,
hash_fn: u64,
namespace: FnNamespace
) -> &mut Self
pub fn update_fn_namespace(
&mut self,
hash_fn: u64,
namespace: FnNamespace
) -> &mut Self
Update the namespace of a registered function.
The u64
hash is returned by the set_native_fn
call.
sourcepub fn set_fn(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
func: CallableFunction
) -> u64
pub fn set_fn(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
func: CallableFunction
) -> u64
Set a Rust function into the Module
, returning a non-zero hash key.
If there is an existing Rust function of the same hash, it is replaced.
WARNING - Low Level API
This function is very low level.
Parameter Names and Types
Each parameter name/type pair should be a single string of the format: var_name: type
.
Return Type
The last entry in the list should be the return type of the function. In other words, the number of entries should be one larger than the number of parameters.
sourcepub fn set_fn_with_comments<S: AsRef<str>>(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
comments: impl AsRef<[S]>,
func: CallableFunction
) -> u64
pub fn set_fn_with_comments<S: AsRef<str>>(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
comments: impl AsRef<[S]>,
func: CallableFunction
) -> u64
(metadata) Set a Rust function into the Module
, returning a non-zero hash key.
Exported under the metadata
feature only.
If there is an existing Rust function of the same hash, it is replaced.
WARNING - Low Level API
This function is very low level.
Parameter Names and Types
Each parameter name/type pair should be a single string of the format: var_name: type
.
Return Type
The last entry in the list should be the return type of the function. In other words, the number of entries should be one larger than the number of parameters.
Comments
Block doc-comments should be kept in a single line.
Line doc-comments should be kept in one string slice per line without the termination line-break.
Leading white-spaces should be stripped, and each string slice always starts with the corresponding
doc-comment leader: ///
or /**
.
sourcepub fn set_raw_fn<T, F>(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_types: impl AsRef<[TypeId]>,
func: F
) -> u64 where
T: Variant + Clone,
F: Fn(NativeCallContext<'_>, &mut [&'_ mut Dynamic]) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
pub fn set_raw_fn<T, F>(
&mut self,
name: impl AsRef<str>,
namespace: FnNamespace,
access: FnAccess,
arg_types: impl AsRef<[TypeId]>,
func: F
) -> u64 where
T: Variant + Clone,
F: Fn(NativeCallContext<'_>, &mut [&'_ mut Dynamic]) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
Set a Rust function taking a reference to the scripting Engine
,
the current set of functions, plus a list of mutable Dynamic
references
into the Module
, returning a non-zero hash key.
Use this to register a built-in function which must reference settings on the scripting
Engine
(e.g. to prevent growing an array beyond the allowed maximum size),
or to call a script-defined function in the current evaluation context.
If there is a similar existing Rust function, it is replaced.
WARNING - Low Level API
This function is very low level.
Arguments
A list of TypeId
’s is taken as the argument types.
Arguments are simply passed in as a mutable array of &mut Dynamic
,
which is guaranteed to contain enough arguments of the correct types.
The function is assumed to be a method, meaning that the first argument should not be consumed. All other arguments can be consumed.
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 std::mem::take(args[n]).cast::<T>()
.
Notice that this will consume the argument, replacing it with ()
.
To access the first mutable argument, use args.get_mut(0).unwrap()
Function Metadata
No metadata for the function is registered. Use update_fn_metadata
to add metadata.
Example
use rhai::{Module, FnNamespace, FnAccess};
let mut module = Module::new();
let hash = module.set_raw_fn("double_or_not", FnNamespace::Internal, FnAccess::Public,
// Pass parameter types via a slice with TypeId's
&[std::any::TypeId::of::<i64>(), std::any::TypeId::of::<bool>()],
// Fixed closure signature
|context, args| {
// 'args' is guaranteed to be the right length and of the correct types
// Get the second parameter by 'consuming' it
let double = std::mem::take(args[1]).cast::<bool>();
// Since it is a primary type, it can also be cheaply copied
let double = args[1].clone_cast::<bool>();
// Get a mutable reference to the first argument.
let mut x = args[0].write_lock::<i64>().unwrap();
let orig = *x;
if double {
*x *= 2; // the first argument can be mutated
}
Ok(orig) // return RhaiResult<T>
});
assert!(module.contains_fn(hash));
sourcepub fn set_native_fn<ARGS, N, T, F>(&mut self, name: N, func: F) -> u64 where
N: AsRef<str> + Into<Identifier>,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
pub fn set_native_fn<ARGS, N, T, F>(&mut self, name: N, func: F) -> u64 where
N: AsRef<str> + Into<Identifier>,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
Set a Rust function into the Module
, returning a non-zero hash key.
If there is a similar existing Rust function, it is replaced.
Function Namespace
The default function namespace is FnNamespace::Internal
.
Use update_fn_namespace
to change it.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
let mut module = Module::new();
let hash = module.set_native_fn("calc", || Ok(42_i64));
assert!(module.contains_fn(hash));
sourcepub fn set_getter_fn<ARGS, A, T, F>(
&mut self,
name: impl AsRef<str>,
func: F
) -> u64 where
A: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
pub fn set_getter_fn<ARGS, A, T, F>(
&mut self,
name: impl AsRef<str>,
func: F
) -> u64 where
A: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
Set a Rust getter function taking one mutable parameter, returning a non-zero hash key. This function is automatically exposed to the global namespace.
If there is a similar existing Rust getter function, it is replaced.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
let mut module = Module::new();
let hash = module.set_getter_fn("value", |x: &mut i64| { Ok(*x) });
assert!(module.contains_fn(hash));
sourcepub fn set_setter_fn<ARGS, A, B, F>(
&mut self,
name: impl AsRef<str>,
func: F
) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
pub fn set_setter_fn<ARGS, A, B, F>(
&mut self,
name: impl AsRef<str>,
func: F
) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
Set a Rust setter function taking two parameters (the first one mutable) into the Module
,
returning a non-zero hash key.
This function is automatically exposed to the global namespace.
If there is a similar existing setter Rust function, it is replaced.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
use rhai::{Module, ImmutableString};
let mut module = Module::new();
let hash = module.set_setter_fn("value", |x: &mut i64, y: ImmutableString| {
*x = y.len() as i64;
Ok(())
});
assert!(module.contains_fn(hash));
sourcepub fn set_indexer_get_fn<ARGS, A, B, T, F>(&mut self, func: F) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
pub fn set_indexer_get_fn<ARGS, A, B, T, F>(&mut self, func: F) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<T, Box<EvalAltResult>>>,
F: Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
Set a Rust index getter taking two parameters (the first one mutable) into the Module
,
returning a non-zero hash key.
This function is automatically exposed to the global namespace.
If there is a similar existing setter Rust function, it is replaced.
Panics
Panics if the type is Array
or Map
.
Indexers for arrays, object maps and strings cannot be registered.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
use rhai::{Module, ImmutableString};
let mut module = Module::new();
let hash = module.set_indexer_get_fn(|x: &mut i64, y: ImmutableString| {
Ok(*x + y.len() as i64)
});
assert!(module.contains_fn(hash));
sourcepub fn set_indexer_set_fn<ARGS, A, B, C, F>(&mut self, func: F) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
C: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B, C) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
pub fn set_indexer_set_fn<ARGS, A, B, C, F>(&mut self, func: F) -> u64 where
A: Variant + Clone,
B: Variant + Clone,
C: Variant + Clone,
F: RegisterNativeFunction<ARGS, Result<(), Box<EvalAltResult>>>,
F: Fn(&mut A, B, C) -> Result<(), Box<EvalAltResult>> + SendSync + 'static,
Set a Rust index setter taking three parameters (the first one mutable) into the Module
,
returning a non-zero hash key.
This function is automatically exposed to the global namespace.
If there is a similar existing Rust function, it is replaced.
Panics
Panics if the type is Array
or Map
.
Indexers for arrays, object maps and strings cannot be registered.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
use rhai::{Module, ImmutableString};
let mut module = Module::new();
let hash = module.set_indexer_set_fn(|x: &mut i64, y: ImmutableString, value: i64| {
*x = y.len() as i64 + value; Ok(())
});
assert!(module.contains_fn(hash));
sourcepub fn set_indexer_get_set_fn<A, B, T>(
&mut self,
get_fn: impl Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
set_fn: impl Fn(&mut A, B, T) -> Result<(), Box<EvalAltResult>> + SendSync + 'static
) -> (u64, u64) where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
pub fn set_indexer_get_set_fn<A, B, T>(
&mut self,
get_fn: impl Fn(&mut A, B) -> Result<T, Box<EvalAltResult>> + SendSync + 'static,
set_fn: impl Fn(&mut A, B, T) -> Result<(), Box<EvalAltResult>> + SendSync + 'static
) -> (u64, u64) where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
Set a pair of Rust index getter and setter functions, returning both non-zero hash keys.
This is a short-hand for set_indexer_get_fn
and
set_indexer_set_fn
.
If there are similar existing Rust functions, they are replaced.
Panics
Panics if the type is Array
or Map
.
Indexers for arrays, object maps and strings cannot be registered.
Function Metadata
No metadata for the function is registered.
Use update_fn_metadata
to add metadata.
Example
use rhai::{Module, ImmutableString};
let mut module = Module::new();
let (hash_get, hash_set) = module.set_indexer_get_set_fn(
|x: &mut i64, y: ImmutableString| {
Ok(*x + y.len() as i64)
},
|x: &mut i64, y: ImmutableString, value: i64| {
*x = y.len() as i64 + value; Ok(())
}
);
assert!(module.contains_fn(hash_get));
assert!(module.contains_fn(hash_set));
sourcepub fn contains_qualified_fn(&self, hash_fn: u64) -> bool
pub fn contains_qualified_fn(&self, hash_fn: u64) -> bool
Does the particular namespace-qualified function exist in the Module
?
The u64
hash is calculated by build_index
.
sourcepub fn combine_flatten(&mut self, other: Self) -> &mut Self
pub fn combine_flatten(&mut self, other: Self) -> &mut Self
sourcepub fn count(&self) -> (usize, usize, usize)
pub fn count(&self) -> (usize, usize, usize)
Get the number of variables, functions and type iterators in the Module
.
sourcepub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, &Shared<Module>)>
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, &Shared<Module>)>
Get an iterator to the sub-modules in the Module
.
sourcepub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)>
pub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)>
Get an iterator to the variables in the Module
.
sourcepub fn iter_script_fn_info(
&self
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize, &Shared<ScriptFnDef>)>
pub fn iter_script_fn_info(
&self
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize, &Shared<ScriptFnDef>)>
(internals) Get an iterator over all script-defined functions in the Module
.
Exported under the internals
feature only.
Function metadata includes:
- Namespace (
FnNamespace::Global
orFnNamespace::Internal
). - Access mode (
FnAccess::Public
orFnAccess::Private
). - Function name (as string slice).
- Number of parameters.
- (internals) Shared reference to function definition
ScriptFnDef
.
sourcepub fn eval_ast_as_new(
scope: Scope<'_>,
ast: &AST,
engine: &Engine
) -> Result<Self, Box<EvalAltResult>>
pub fn eval_ast_as_new(
scope: Scope<'_>,
ast: &AST,
engine: &Engine
) -> Result<Self, Box<EvalAltResult>>
Create a new Module
by evaluating an AST
.
The entire AST
is encapsulated into each function, allowing functions
to cross-call each other. Functions in the global namespace, plus all functions
defined in the Module
, are merged into a unified namespace before each call.
Therefore, all functions will be found.
Example
use rhai::{Engine, Module, Scope};
let engine = Engine::new();
let ast = engine.compile("let answer = 42; export answer;")?;
let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?;
assert!(module.contains_var("answer"));
assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
sourcepub fn contains_indexed_global_functions(&self) -> bool
pub fn contains_indexed_global_functions(&self) -> bool
Does the Module
contain indexed functions that have been exposed to the global namespace?
Panics
Panics if the Module
is not yet indexed via build_index
.
sourcepub fn build_index(&mut self) -> &mut Self
pub fn build_index(&mut self) -> &mut Self
sourcepub fn contains_qualified_iter(&self, id: TypeId) -> bool
pub fn contains_qualified_iter(&self, id: TypeId) -> bool
Does a type iterator exist in the entire module tree?
sourcepub fn contains_iter(&self, id: TypeId) -> bool
pub fn contains_iter(&self, id: TypeId) -> bool
Does a type iterator exist in the module?
sourcepub fn set_iter(
&mut self,
type_id: TypeId,
func: impl Fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + 'static
) -> &mut Self
pub fn set_iter(
&mut self,
type_id: TypeId,
func: impl Fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + 'static
) -> &mut Self
Set a type iterator into the Module
.
sourcepub fn set_iterable<T>(&mut self) -> &mut Self where
T: Variant + Clone + IntoIterator,
<T as IntoIterator>::Item: Variant + Clone,
pub fn set_iterable<T>(&mut self) -> &mut Self where
T: Variant + Clone + IntoIterator,
<T as IntoIterator>::Item: Variant + Clone,
Set a type iterator into the Module
.
Trait Implementations
sourceimpl<M: Into<Module>> AddAssign<M> for Module
impl<M: Into<Module>> AddAssign<M> for Module
sourcefn add_assign(&mut self, rhs: M)
fn add_assign(&mut self, rhs: M)
Performs the +=
operation. Read more
Auto Trait Implementations
impl !RefUnwindSafe for Module
impl !Send for Module
impl !Sync for Module
impl Unpin for Module
impl !UnwindSafe for Module
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> ToOwned for T where
T: Clone,
impl<T> ToOwned for T where
T: Clone,
type Owned = T
type Owned = T
The resulting type after obtaining ownership.
sourcefn clone_into(&self, target: &mut T)
fn clone_into(&self, target: &mut T)
toowned_clone_into
)Uses borrowed data to replace owned data, usually by cloning. Read more