4 releases

0.1.3 Jun 1, 2022
0.1.2 Jun 1, 2022
0.1.1 Nov 20, 2021
0.1.0 Nov 19, 2021

#110 in Embedded development

44 downloads per month


109 lines

rhai-rand - Package to Generate Random Numbers

License crates.io crates.io

Rhai logo

rhai-rand is a Rhai package to provide random number generation using the rand crate.

Rhai is an embedded scripting language and evaluation engine for Rust that gives a safe and easy way to add scripting to any application.



rhai-rand = "0.1"

Rhai script

// Create random boolean
let decision = rand_bool();

if decision {
    // Create random number
    let random_value = rand();
    print(`Random number = ${random_value}`);
} else {
    print("Fixed number = 42");

// Create array
let a = [1, 2, 3, 4, 5];

// Shuffle it!

// Now the array is shuffled randomly!

// Sample a random value from the array

// Or sample multiple values

Rust source

// packages::Package implements `as_shared_module`
// which we need to register the RandomPackage
use rhai::{Engine, packages::Package};
use rhai_rand::RandomPackage;

// Create Rhai scripting engine
let mut engine = Engine::new();

// Create random number package and add the package into the engine

// Print 10 random numbers, each of which between 0-99!
for _ in 0..10 {
    let value = engine.eval::<INT>("(rand() % 100).abs()")?;

    println!("Random number = {}", value);


Feature Default Description
metadata disabled includes functions metadata: parameter names/types, return type, doc-comments
decimal Disabled provides random decimal number generation
float enabled provides random floating-point number generation
array enabled provides methods for Rhai arrays


The following functions are defined in this package:

Function Return value Feature Description
rand() INT generates a random number
rand_float() FLOAT float generates a random floating-point number between 0.0 and 1.0
rand_decimal() Decimal decimal generates a random decimal number
rand_bool() bool generates a random boolean
Array.shuffle() array shuffles the items in the Rhai array
Array.sample() Dynamic array copies a random element from the Rhai array
Array.sample(n) Array array copies a non-repeating random sample of elements from the Rhai array


~66K SLoC