Packages

The built-in library of Rhai is provided as various packages that can be turned into shared modules, which in turn can be registered into the global namespace of an Engine via Engine::register_global_module.

Packages reside under rhai::packages::* and the trait rhai::packages::Package must be loaded in order for packages to be used.

Trivia: Packages are modules!

Internally, a package is a module, with some conveniences to make it easier to define and use as a standard library for an Engine.

Packages typically contain Rust functions that are callable within a Rhai script. All top-level functions in a package are available under the global namespace (i.e. they’re available without namespace qualifiers).

Sub-modules and variables are ignored in packages.

Share a Package Among Multiple Engine’s

Engine::register_global_module and Engine::register_static_module both require shared modules.

Once a package is created (e.g. via Package::new), it can be registered into multiple instances of Engine, even across threads (under the sync feature).

Tip: Sharing package

A package only has to be created once and essentially shared among multiple Engine instances.

This is particularly useful when spawning large number of raw Engine’s.

use rhai::Engine;
use rhai::packages::Package         // load the 'Package' trait to use packages
use rhai::packages::CorePackage;    // the 'core' package contains basic functionalities (e.g. arithmetic)

// Create a package - can be shared among multiple 'Engine' instances
let package = CorePackage::new();

let mut engines_collection: Vec<Engine> = Vec::new();

// Create 100 'raw' Engines
for _ in 0..100 {
    let mut engine = Engine::new_raw();

    // Register the package into the global namespace.
    package.register_into_engine(&mut engine);

    engines_collection.push(engine);
}