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 example
assignment.rhaivariable declarations
comments.rhaijust regular comments
doc-comments.rhaidoc-comments example
for1.rhaifor loops
for2.rhaifor loops with array iterations
for3.rhaifor loops with closures
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 dowhile 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
strings_map.rhaistring and object map operations
switch.rhaiswitch example
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

Run Example Scripts

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

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