Struct quad_compat_rhai::plugin::Module[][src]

pub struct Module { /* fields omitted */ }
Expand description

A module which may contain variables, sub-modules, external Rust functions, and/or script-defined functions.

Implementations

Create a new Module.

Example
let mut module = Module::new();
module.set_var("answer", 42_i64);
assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);

Get the ID of the Module, if any.

Example
let mut module = Module::new();
module.set_id("hello");
assert_eq!(module.id(), Some("hello"));

Set the ID of the Module.

Example
let mut module = Module::new();
module.set_id("hello");
assert_eq!(module.id(), Some("hello"));

Clear the ID of the Module.

Example
let mut module = Module::new();
module.set_id("hello");
assert_eq!(module.id(), Some("hello"));
module.clear_id();
assert_eq!(module.id(), None);

Is the Module empty?

Example
let module = Module::new();
assert!(module.is_empty());

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());

Generate signatures for all the non-private functions in the Module. Exported under the metadata feature only.

Does a variable exist in the Module?

Example
let mut module = Module::new();
module.set_var("answer", 42_i64);
assert!(module.contains_var("answer"));

Get the value of a Module variable.

Example
let mut module = Module::new();
module.set_var("answer", 42_i64);
assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);

Get a Module variable as a Dynamic.

Example
let mut module = Module::new();
module.set_var("answer", 42_i64);
assert_eq!(module.get_var("answer").expect("answer should exist").cast::<i64>(), 42);

Set a variable into the Module.

If there is an existing variable of the same name, it is replaced.

Example
let mut module = Module::new();
module.set_var("answer", 42_i64);
assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);

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.

Get a shared reference to the script-defined function in the Module based on name and number of parameters.

Does a sub-module exist in the Module?

Example
let mut module = Module::new();
let sub_module = Module::new();
module.set_sub_module("question", sub_module);
assert!(module.contains_sub_module("question"));

Get a sub-module in the Module.

Example
let mut module = Module::new();
let sub_module = Module::new();
module.set_sub_module("question", sub_module);
assert!(module.get_sub_module("question").is_some());

Set a sub-module into the Module.

If there is an existing sub-module of the same name, it is replaced.

Example
let mut module = Module::new();
let sub_module = Module::new();
module.set_sub_module("question", sub_module);
assert!(module.get_sub_module("question").is_some());

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));

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.

Update the namespace of a registered function.

The u64 hash is returned by the set_native_fn call.

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.

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 quad_compat_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 Result<T, Box<EvalAltResult>>
                });

assert!(module.contains_fn(hash));

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));

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));

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 quad_compat_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));

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 quad_compat_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));

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 quad_compat_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));

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 quad_compat_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));

Does the particular namespace-qualified function exist in the Module?

The u64 hash is calculated by build_index.

Combine another Module into this Module. The other Module is consumed to merge into this Module.

Combine another Module into this Module. The other Module is consumed to merge into this Module. Sub-modules are flattened onto the root Module, with higher level overriding lower level.

Polyfill this Module with another Module. Only items not existing in this Module are added.

Merge another Module into this Module.

Get the number of variables, functions and type iterators in the Module.

Get an iterator to the sub-modules in the Module.

Get an iterator to the variables in the Module.

(internals) Get an iterator over all script-defined functions in the Module. Exported under the internals feature only.

Function metadata includes:

  1. Namespace (FnNamespace::Global or FnNamespace::Internal).
  2. Access mode (FnAccess::Public or FnAccess::Private).
  3. Function name (as string slice).
  4. Number of parameters.
  5. (internals) Shared reference to function definition ScriptFnDef.

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 quad_compat_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);

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.

Scan through all the sub-modules in the Module and build a hash index of all variables and functions as one flattened namespace.

If the Module is already indexed, this method has no effect.

Does a type iterator exist in the entire module tree?

Does a type iterator exist in the module?

Set a type iterator into the Module.

Set a type iterator into the Module.

Set an iterator type into the Module as a type iterator.

Trait Implementations

The resulting type after applying the + operator.

Performs the + operation. Read more

The resulting type after applying the + operator.

Performs the + operation. Read more

Performs the += operation. Read more

Performs the conversion.

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Performs the conversion.

The resulting type after obtaining ownership.

Creates owned data from borrowed data, usually by cloning. Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into)

Uses borrowed data to replace owned data, usually by cloning. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.