Expand description
§Rhai - embedded scripting for Rust
Rhai is a tiny, simple and fast embedded scripting language for Rust that gives you a safe and easy way to add scripting to your applications.
It provides a familiar syntax based on JavaScript+Rust and a simple Rust interface.
§A Quick Example
§Contents of my_script.rhai
/// Brute force factorial function
fn factorial(x) {
if x == 1 { return 1; }
x * factorial(x - 1)
}
// Calling an external function 'compute'
compute(factorial(10))§The Rust part
use rhai::{Engine, EvalAltResult};
fn main() -> Result<(), Box<EvalAltResult>>
{
// Define external function
fn compute_something(x: i64) -> bool {
(x % 40) == 0
}
// Create scripting engine
let mut engine = Engine::new();
// Register external function as 'compute'
engine.register_fn("compute", compute_something);
// Evaluate the script, expecting a 'bool' result
let result: bool = engine.eval_file("my_script.rhai".into())?;
assert_eq!(result, true);
Ok(())
}§Features
default— Default features:std, uses runtime random numbers for hashing.std(enabled by default) — Standard features: uses compile-time random number for hashing.
§Enable Special Functionalities
sync— Require that all data types implementSend + Sync(for multi-threaded usage).decimal— Add support for theDecimaldata type (acts as the system floating-point type underno_float).serde— Enable serialization/deserialization of Rhai data types viaserde.unicode-xid-ident— Allow Unicode Standard Annex #31 for identifiers.metadata— Enable functions metadata (including doc-comments); impliesserde.internals— Expose internal data structures (e.g.ASTnodes).debugging— Enable the debugging interface (impliesinternals).bin-features— Features and dependencies required bybintools:decimal,metadata,serde,debuggingandrustyline.fuzz— Enable fuzzing via thearbitrarycrate.
§System Configuration Features
f32_float— Usef32instead off64as the system floating-point number type.only_i32— Usei32instead ofi64for the system integer number type (useful for 32-bit architectures). All other integer types (e.g.u8) are disabled.only_i64— Disable all integer types (e.g.u8) other thani64.
§Disable Language Features
no_float— Remove support for floating-point numbers.no_index— Remove support for arrays and indexing.no_object— Remove support for custom types, properties, method-style calls and object maps.no_time— Remove support for time-stamps.no_function— Remove support for script-defined functions (impliesno_closure).no_closure— Remove support for capturing external variables in anonymous functions (i.e. closures).no_module— Remove support for loading external modules.no_custom_syntax— Remove support for custom syntax.
§Performance-Related Features
unchecked— Disable all safety checks.no_position— Do not track position when parsing.no_optimize— Disable the script optimizer.
§Compiling for no-std
no_std— Turn onno-stdcompilation (nightly only).
§JavaScript Interface for WASM
wasm-bindgen— Usewasm-bindgenas JavaScript interface.stdweb— Usestdwebas JavaScript interface.
§Features used in testing environments only
unstable— Compiled with a non-stable compiler (i.e. beta or nightly)testing-environ— Running under a testing environment.
§On-Line Documentation
See The Rhai Book for details on the Rhai scripting engine and language.
Modules§
- config
- Configuration for Rhai.
- debugger
- (debugging) Module containing types for debugging.
Exported under the
debuggingfeature only. - default_
limits - Default limits.
- module_
resolvers - Module containing all built-in module resolvers available to Rhai. Module containing all built-in module resolvers.
- packages
- Module containing all built-in packages available to Rhai, plus facilities to define custom packages.
- plugin
- Module defining macros for developing plugins.
- serde
- (serde) Serialization and deserialization support for
serde. Exported under theserdefeature only.
Macros§
- combine_
with_ exported_ module - Macro to combine a plugin module into an existing module.
- def_
package - Macro that makes it easy to define a package (which is basically a shared module) and register functions into it.
- exported_
module - Macro to generate a Rhai
Modulefrom a plugin module defined via#[export_module]. - register_
exported_ fn - Macro to register a plugin function (defined via
#[export_fn]) into anEngine. - set_
exported_ fn - Macro to register a plugin function into a Rhai
Module. - set_
exported_ global_ fn - Macro to register a plugin function into a Rhai
Moduleand expose it globally.
Structs§
- AST
- Compiled AST (abstract syntax tree) of a Rhai script.
- ASTFlags
- (internals) Bit-flags containing
ASTnode configuration options. Exported under theinternalsfeature only. - Binary
Expr - (internals) A binary expression.
Exported under the
internalsfeature only. - Bloom
Filter U64 - (internals) A simple bloom filter implementation for
u64hash values only - i.e. all 64 bits are assumed to be relatively random. Exported under theinternalsfeature only. - Caches
- (internals) A type containing system-wide caches.
Exported under the
internalsfeature only. - Call
FnOptions - Options for calling a script-defined function via
Engine::call_fn_with_options. - Custom
Expr - (internals) A custom syntax expression.
Exported under the
internalsfeature only. - Custom
Type Info - (internals) Information for a registered custom type.
Exported under the
internalsfeature only. - Definitions
- (metadata, internals) Definitions helper type to generate definition files based on the
contents of an
Engine. Exported under theinternalsandmetadatafeature only. - Dynamic
- Dynamic type containing any value.
- Dynamic
Read Lock - (internals) Lock guard for reading a
Dynamic. Exported under theinternalsfeature only. - Dynamic
Write Lock - (internals) Lock guard for writing a
Dynamic. Exported under theinternalsfeature only. - Encapsulated
Environ - (internals) Encapsulated AST environment.
Exported under the
internalsfeature only. - Engine
- Rhai main scripting engine.
- Eval
Context - Context of a script evaluation process.
- Expression
- An expression sub-tree in an
AST. - Float
Wrapper - (internals) A type that wraps a floating-point number and implements
Hash. Exported under theinternalsfeature only. - Flow
Control - (internals) A flow control block containing:
- FnCall
Expr - (internals) A function call.
Exported under the
internalsfeature only. - FnCall
Hashes - (internals) A set of function call hashes. Exported under the
internalsfeature only. - FnPtr
- A general function pointer, which may carry additional (i.e. curried) argument values to be passed onto a function during a call.
- FnResolution
Cache - (internals) A function resolution cache with a bloom filter.
Exported under the
internalsfeature only. - FnResolution
Cache Entry - (internals) An entry in a function resolution cache.
Exported under the
internalsfeature only. - Func
Info - Information about a function, native or scripted.
- Func
Metadata - (internals) A type containing the metadata of a single registered function.
Exported under the
internalsfeatures only. - Func
Registration - Type for fine-tuned module function registration.
- Global
Runtime State - (internals) Global runtime states.
Exported under the
internalsfeature only. - Ident
- (internals) An identifier containing a name and a position.
Exported under the
internalsfeature only. - Immutable
String - The system immutable string type.
- Instant
- A measurement of a monotonically nondecreasing clock.
Opaque and useful only with
Duration. - Locked
- Alias to
RefCellorRwLockdepending on thesyncfeature flag. Synchronized shared object. A mutable memory location with dynamically checked borrow rules - Module
- A module which may contain variables, sub-modules, external Rust functions, and/or script-defined functions.
- Multi
Inputs Stream - (internals) A type that implements the
InputStreamtrait. Exported under theinternalsfeature only. - Namespace
- (internals) A chain of module names to namespace-qualify a variable or function call.
Exported under the
internalsfeature only. - Native
Call Context - Context of a native Rust function call.
- Native
Call Context Store Deprecated - (internals) Context of a native Rust function call, intended for persistence.
Exported under the
internalsfeature only. - OpAssignment
- (internals) An op-assignment operator.
Exported under the
internalsfeature only. - Parse
Error - Error when parsing a script.
- Parse
State - (internals) A type that encapsulates the current state of the parser.
Exported under the
internalsfeature only. - Position
- A location (line number + character position) in the input script.
- Scope
- Type containing information about the current scope. Useful for keeping state between
Engineevaluation runs. - Script
FnMetadata - A type containing the metadata of a script-defined function.
- Script
Func Def - (internals) A type containing information on a script-defined function.
Exported under the
internalsfeature only. - Shared
- Alias to
RcorArcdepending on thesyncfeature flag. Immutable reference-counted container. A single-threaded reference-counting pointer. ‘Rc’ stands for ‘Reference Counted’. - Span
- (internals) A span consisting of a starting and an ending positions.
Exported under the
internalsfeature only. - Stmt
Block - (internals) A scoped block of statements.
Exported under the
internalsfeature only. - Strings
Interner - (internals) A cache for interned strings.
Exported under the
internalsfeature only. - Switch
Cases Collection - (internals) A type containing all cases for a
switchstatement. Exported under theinternalsfeature only. - Token
Iterator - (internals) An iterator on a
Tokenstream. Exported under theinternalsfeature only. - Tokenize
State - (internals) State of the tokenizer.
Exported under the
internalsfeature only. - Tokenizer
Control Block - (internals) A type containing commands to control the tokenizer.
- Type
Builder - Builder to build the API of a custom type for use with an
Engine. - VarDef
Info - Information on a variable declaration.
Enums§
- ASTNode
- (internals) An
ASTnode, consisting of either anExpror aStmt. Exported under theinternalsfeature only. - Access
Mode - (internals) Modes of access.
Exported under the
internalsfeature only. - Eval
AltResult - Evaluation result.
- Expr
- (internals) An expression sub-tree.
Exported under the
internalsfeature only. - FnAccess
- A type representing the access mode of a function.
- FnNamespace
- A type representing the namespace of a function.
- LexError
- Error encountered when tokenizing the script text.
- Optimization
Level - Level of optimization performed.
- Parse
Error Type - Error encountered when parsing a script.
- Range
Case - (internals) A type containing a range case for a
switchstatement. Exported under theinternalsfeature only. - Rhai
Func - (internals) A type encapsulating a function callable by Rhai.
Exported under the
internalsfeature only. - Stmt
- (internals) A statement.
Exported under the
internalsfeature only. - Target
- (internals) A type that encapsulates a mutation target for an expression with side effects.
Exported under the
internalsfeature only. - Token
- (internals) A Rhai language token.
Exported under the
internalsfeature only.
Constants§
- FUNC_
TO_ DEBUG - Standard debug-print function.
- FUNC_
TO_ STRING - Standard pretty-print function.
- OP_
CONTAINS - Standard containment testing function.
- OP_
EQUALS - Standard equality comparison operator.
Traits§
- Custom
Type - Trait to build the API of a custom type for use with an
Engine(i.e. register the type and its getters, setters, methods, etc.). - Func
- Trait to create a Rust closure from a script.
- Func
Args - Trait that parses arguments to a function call.
- Input
Stream - (internals) Trait that encapsulates a peekable character input stream.
Exported under the
internalsfeature only. - Module
Resolver - Trait that encapsulates a module resolution service.
- Rhai
Native Func - Trait to register custom Rust functions.
- Variant
- (internals) Trait to represent any type.
Exported under the
internalsfeature only.
Functions§
- eval
- Evaluate a string as a script, returning the result value or an error.
- eval_
file - Evaluate a script file, returning the result value or an error.
- format_
map_ as_ json - Return the JSON representation of an object map.
- get_
next_ token - (internals) Get the next token from the input stream.
Exported under the
internalsfeature only. - is_
valid_ function_ name - (internals) Is a text string a valid script-defined function name?
Exported under the
internalsfeature only. - is_
valid_ identifier - (internals) Is a text string a valid identifier?
Exported under the
internalsfeature only. - locked_
read - (internals) Lock a
Lockedresource for immutable access. Exported under theinternalsfeature only. - locked_
write - (internals) Lock a
Lockedresource for mutable access. Exported under theinternalsfeature only. - parse_
raw_ string_ literal - (internals) Parse a raw string literal. Exported under the
internalsfeature only. - parse_
string_ literal - (internals) Parse a string literal ended by a specified termination character.
Exported under the
internalsfeature only. - run
- Evaluate a string as a script.
- run_
file - Evaluate a file.
Type Aliases§
- Array
- Variable-sized array of
Dynamicvalues. - Blob
- Variable-sized array of
u8values (byte array). - FLOAT
- The system floating-point type. It is defined as
f64. - FnArgs
Vec - (internals) Inline arguments storage for function calls.
Exported under the
internalsfeature only. - INT
- The system integer type. It is defined as
i64. - Identifier
- (internals) An identifier in Rhai.
Exported under the
internalsfeature only. - Map
- A dictionary of
Dynamicvalues with string keys. - Static
Vec - (internals) Alias to
smallvec::SmallVec<[T; 3]>, which is aVecbacked by a small, inline, fixed-size array when there are ≤ 3 items stored. Exported under theinternalsfeature only. - ThinVec
- (internals) A smaller
Vecalternative. Exported under theinternalsfeature only. Exported under theinternalsfeature only. - Tokenizer
Control - (internals) A shared object that allows control of the tokenizer from outside.
Attribute Macros§
- export_
fn - Attribute, when put on a Rust function, turns it into a plugin function.
- export_
module - Attribute, when put on a Rust module, turns it into a plugin module.
- expose_
under_ internals - Macro to automatically expose a Rust function, type-def or use statement as
pubwhen under theinternalsfeature.
Derive Macros§
- Custom
Type - Macro to implement the [
CustomType][rhai::CustomType] trait.