This repository has been archived on 2025-08-04. You can view files and clone it, but cannot push or open issues or pull requests.
rhaj/rhai_engine/rhaibook/start/examples/rust.md
2025-04-03 09:18:05 +02:00

5.5 KiB

Rust Examples

{{#include ../../links.md}}

Standard Examples

A number of examples can be found under examples.

Example Description
arrays_and_structs shows how to register a [Rust type][custom type] and using it with [arrays]
callback shows how to store a Rhai [closure] and call it later within Rust
custom_types_and_methods shows how to register a [Rust type][custom type] and [methods]/[getters/setters] for it
custom_types shows how to register a [Rust type][custom type] and [methods]/[getters/setters] using the [CustomType] trait.
definitions shows how to generate definition files for use with the [Rhai Language Server][lsp] (requires the [metadata] feature)
hello simple example that evaluates an expression and prints the result
pause_and_resume shows how to pause/resume/stop an Engine running in a separate thread via an MPSC channel
reuse_scope evaluates two pieces of code in separate runs, but using a common [Scope]
serde example to serialize and deserialize Rust types with serde (requires the [serde] feature)
simple_fn shows how to register a simple Rust function
strings shows different ways to register Rust functions taking [string] arguments
threading shows how to communicate in duplex with an [Engine] running in a separate thread via a pair of MPSC channels

Scriptable Event Handler With State Examples

Because of its popularity, the pattern Scriptable Event Handler With State has sample implementations for different styles.

Example Handler Script Description
event_handler_main event_handler_main/script.rhai Main Style
event_handler_js event_handler_js/script.rhai JS Style
event_handler_map event_handler_map/script.rhai Map Style

Running Examples

Examples can be run with the following command:

cargo run --example {example_name}

no-std Examples

To illustrate no-std builds, a number of example applications are available under the no_std directory:

Example Description Optimization Allocator Panics
no_std_test bare-bones test application that evaluates a Rhai expression and sets the result as the return value size wee_alloc abort

Building the no-std examples


Currently, the nightly compiler must be used to build for `no-std`.
cd no_std/no_std_test

cargo +nightly build --release

./target/release/no_std_test