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 theDecimal
data 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.AST
nodes).debugging
— Enable the debugging interface (impliesinternals
).bin-features
— Features and dependencies required bybin
tools:decimal
,metadata
,serde
,debugging
andrustyline
.fuzz
— Enable fuzzing via thearbitrary
crate.
§System Configuration Features
f32_float
— Usef32
instead off64
as the system floating-point number type.only_i32
— Usei32
instead ofi64
for 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-std
compilation (nightly only).
§JavaScript Interface for WASM
wasm-bindgen
— Usewasm-bindgen
as JavaScript interface.stdweb
— Usestdweb
as 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
debugging
feature 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 theserde
feature 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
Module
from 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
Module
and expose it globally.
Structs§
- AST
- Compiled AST (abstract syntax tree) of a Rhai script.
- ASTFlags
- (internals) Bit-flags containing
AST
node configuration options. Exported under theinternals
feature only. - Binary
Expr - (internals) A binary expression.
Exported under the
internals
feature only. - Bloom
Filter U64 - (internals) A simple bloom filter implementation for
u64
hash values only - i.e. all 64 bits are assumed to be relatively random. Exported under theinternals
feature only. - Caches
- (internals) A type containing system-wide caches.
Exported under the
internals
feature 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
internals
feature only. - Custom
Type Info - (internals) Information for a registered custom type.
Exported under the
internals
feature only. - Definitions
- (metadata, internals) Definitions helper type to generate definition files based on the
contents of an
Engine
. Exported under theinternals
andmetadata
feature only. - Dynamic
- Dynamic type containing any value.
- Dynamic
Read Lock - (internals) Lock guard for reading a
Dynamic
. Exported under theinternals
feature only. - Dynamic
Write Lock - (internals) Lock guard for writing a
Dynamic
. Exported under theinternals
feature only. - Encapsulated
Environ - (internals) Encapsulated AST environment.
Exported under the
internals
feature 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 theinternals
feature only. - Flow
Control - (internals) A flow control block containing:
- FnCall
Expr - (internals) A function call.
Exported under the
internals
feature only. - FnCall
Hashes - (internals) A set of function call hashes. Exported under the
internals
feature 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
internals
feature only. - FnResolution
Cache Entry - (internals) An entry in a function resolution cache.
Exported under the
internals
feature 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
internals
features only. - Func
Registration - Type for fine-tuned module function registration.
- Global
Runtime State - (internals) Global runtime states.
Exported under the
internals
feature only. - Ident
- (internals) An identifier containing a name and a position.
Exported under the
internals
feature 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
RefCell
orRwLock
depending on thesync
feature 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
InputStream
trait. Exported under theinternals
feature only. - Namespace
- (internals) A chain of module names to namespace-qualify a variable or function call.
Exported under the
internals
feature 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
internals
feature only. - OpAssignment
- (internals) An op-assignment operator.
Exported under the
internals
feature only. - Parse
Error - Error when parsing a script.
- Parse
State - (internals) A type that encapsulates the current state of the parser.
Exported under the
internals
feature 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
Engine
evaluation 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
internals
feature only. - Shared
- Alias to
Rc
orArc
depending on thesync
feature 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
internals
feature only. - Stmt
Block - (internals) A scoped block of statements.
Exported under the
internals
feature only. - Strings
Interner - (internals) A cache for interned strings.
Exported under the
internals
feature only. - Switch
Cases Collection - (internals) A type containing all cases for a
switch
statement. Exported under theinternals
feature only. - Token
Iterator - (internals) An iterator on a
Token
stream. Exported under theinternals
feature only. - Tokenize
State - (internals) State of the tokenizer.
Exported under the
internals
feature 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
AST
node, consisting of either anExpr
or aStmt
. Exported under theinternals
feature only. - Access
Mode - (internals) Modes of access.
Exported under the
internals
feature only. - Eval
AltResult - Evaluation result.
- Expr
- (internals) An expression sub-tree.
Exported under the
internals
feature 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
switch
statement. Exported under theinternals
feature only. - Rhai
Func - (internals) A type encapsulating a function callable by Rhai.
Exported under the
internals
feature only. - Stmt
- (internals) A statement.
Exported under the
internals
feature only. - Target
- (internals) A type that encapsulates a mutation target for an expression with side effects.
Exported under the
internals
feature only. - Token
- (internals) A Rhai language token.
Exported under the
internals
feature 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
internals
feature 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
internals
feature 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
internals
feature only. - is_
valid_ function_ name - (internals) Is a text string a valid script-defined function name?
Exported under the
internals
feature only. - is_
valid_ identifier - (internals) Is a text string a valid identifier?
Exported under the
internals
feature only. - locked_
read - (internals) Lock a
Locked
resource for immutable access. Exported under theinternals
feature only. - locked_
write - (internals) Lock a
Locked
resource for mutable access. Exported under theinternals
feature only. - parse_
raw_ string_ literal - (internals) Parse a raw string literal. Exported under the
internals
feature only. - parse_
string_ literal - (internals) Parse a string literal ended by a specified termination character.
Exported under the
internals
feature only. - run
- Evaluate a string as a script.
- run_
file - Evaluate a file.
Type Aliases§
- Array
- Variable-sized array of
Dynamic
values. - Blob
- Variable-sized array of
u8
values (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
internals
feature only. - INT
- The system integer type. It is defined as
i64
. - Identifier
- (internals) An identifier in Rhai.
Exported under the
internals
feature only. - Map
- A dictionary of
Dynamic
values with string keys. - Static
Vec - (internals) Alias to
smallvec::SmallVec<[T; 3]>
, which is aVec
backed by a small, inline, fixed-size array when there are ≤ 3 items stored. Exported under theinternals
feature only. - ThinVec
- (internals) A smaller
Vec
alternative. Exported under theinternals
feature only. Exported under theinternals
feature 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
pub
when under theinternals
feature.
Derive Macros§
- Custom
Type - Macro to implement the [
CustomType
][rhai::CustomType] trait.