Example Scripts

Language Feature Scripts

There are also a number of examples scripts that showcase Rhai’s features, all in the scripts directory:

ScriptDescription
array.rhaiarrays
assignment.rhaivariable declarations
comments.rhaijust comments
for1.rhaifor loops
for2.rhaifor loops on arrays
function_decl1.rhaia function without parameters
function_decl2.rhaia function with two parameters
function_decl3.rhaia function with many parameters
function_decl4.rhaia function acting as a method
if1.rhaiif example
if2.rhaiif-expression example
loop.rhaicount-down loop in Rhai, emulating a do .. while loop
module.rhaiimport a script file as a module
oop.rhaisimulate object-oriented programming (OOP) with closures
op1.rhaijust simple addition
op2.rhaisimple addition and multiplication
op3.rhaichange evaluation order with parenthesis
string.rhaistring operations, including interpolation
switch.rhaiswitch example
strings_map.rhaistring and object map operations
while.rhaiwhile loop

Benchmark Scripts

The following scripts are for benchmarking the speed of Rhai:

ScriptsDescription
speed_test.rhaia simple application to measure the speed of Rhai’s interpreter (1 million iterations)
primes.rhaiuse Sieve of Eratosthenes to find all primes smaller than a limit
fibonacci.rhaicalculate the n-th Fibonacci number using a really dumb algorithm
mat_mul.rhaimatrix multiplication test to measure the speed of multi-dimensional array access

Running Example Scripts

The rhai-run utility can be used to run Rhai scripts:

cargo run --bin rhai-run scripts/any_script.rhai