[Avg. reading time: 7 minutes]

Rhai

Rhai is an embedded scripting engine for Rust.

It allows you to run user-defined scripts inside a Rust application without recompiling the code.

  • Rust builds the system
  • Rhai controls behavior at runtime

Execution Flow

Rhai scripts are written in a simple, easy-to-learn syntax. When you execute a Rhai script, it goes through several stages:

Parsing: The script is parsed into an Abstract Syntax Tree (AST). When this script is parsed by Rhai, it gets converted into an AST. The AST is a tree-like structure that represents the syntactic structure of the script.

Compilation: The AST is compiled into an internal representation.

Execution: The compiled script is executed by the Rhai engine.

Script → Parse → AST → Compile → Execute

use rhai::{Engine, Scope};
use std::fs;

fn main() {
    let engine = Engine::new();

    let script = fs::read_to_string("rule1.rhai").unwrap();

    let mut scope = Scope::new();
    scope.push("amount", 1000.0);

    let result: f64 = engine.eval_with_scope(&mut scope, &script).unwrap();

    println!("Final Amount: {}", result);
}

rust1.rhai

// 10% discount
if amount > 500 {
    amount * 0.9
} else {
    amount
}

rule1.rhai

// 20% discount
if amount > 500 {
    amount * 0.8
} else {
    amount
}

Consolidated Example

git clone https://github.com/gchandra10/rust_rhai_demo

Data Engineering Use Case

Dynamic transformation rules

Example:

  • Users define filters: “drop rows where amount < 0”

  • Users define derived columns: “total = price * quantity”

Instead of hardcoding logic, you run Rhai scripts on data rows

Why NOT Use Rhai

  • Slower than native Rust Not suitable for heavy compute loops

  • Not for data processing at scale Don’t run Rhai over 100M rows

  • Limited language features No full Rust-level abstractions

  • Debugging is harder Runtime errors instead of compile-time safety

  • Not for core system logic Only for configurable behavior

Use Cases

Game Development: Embedding Rhai to script game logic, AI behavior, or user interfaces.

Configuration: Allowing users to define configuration scripts that can modify the behavior of an application at runtime.

Automation: Providing a scripting interface for automating tasks or extending the functionality of an application.

Prototyping: Quickly testing and iterating on new features without recompiling the entire Rust application.

RHAI Its not as fast native Rust. Doesn’t support Classes/Traits/Closures/Tuples

#rhai #scriptingVer 2.2.2

Last change: 2026-04-22