Update README with module functions API.

This commit is contained in:
Stephen Chung 2020-05-05 18:26:08 +08:00
parent aae9e43109
commit ff86ae1bd8

View File

@ -2012,6 +2012,8 @@ with `export` statements that _exports_ certain global variables and functions a
Everything exported as part of a module is constant and read-only. Everything exported as part of a module is constant and read-only.
### Importing modules
A module can be _imported_ via the `import` statement, and its members accessed via '`::`' similar to C++. A module can be _imported_ via the `import` statement, and its members accessed via '`::`' similar to C++.
```rust ```rust
@ -2039,6 +2041,33 @@ crypto::encrypt(others); // <- this causes a run-time error because the 'cryp
// is no longer available! // is no longer available!
``` ```
### Creating custom modules from Rust
To load a custom module into an [`Engine`], first create a `Module` type, add variables/functions into it,
then finally push it into a custom [`Scope`]. This has the equivalent effect of putting an `import` statement
at the beginning of any script run.
```rust
use rhai::{Engine, Scope, Module, i64};
let mut engine = Engine::new();
let mut scope = Scope::new();
let mut module = Module::new(); // new module
module.set_var("answer", 41_i64); // variable 'answer' under module
module.set_fn_1("inc", |x: i64| Ok(x+1)); // use the 'set_fn_XXX' API to add functions
// Push the module into the custom scope under the name 'question'
// This is equivalent to 'import "..." as question;'
scope.push_module("question", module);
// Use module-qualified variables
engine.eval_expression_with_scope::<i64>(&scope, "question::answer + 1")? == 42;
// Call module-qualified functions
engine.eval_expression_with_scope::<i64>(&scope, "question::inc(question::answer)")? == 42;
```
Script optimization Script optimization
=================== ===================