Expand description

rhai-rand - Rhai Functions for Random Number Generation

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



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

use rhai::Engine;
use rhai::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-100!
for _ in 0..10 {
    let value = engine.eval::<i64>("rand(0..=100)")?;

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


metadatadisabledincludes functions metadata: parameter names/types, return type, doc-comments
decimalDisabledprovides random decimal number generation
floatenabledprovides random floating-point number generation
arrayenabledprovides methods for Rhai arrays


The following functions are defined in this package:

FunctionReturn typeFeatureDescription
rand()INTgenerates a random number
rand(start..end)INTgenerates a random number within the exclusive range start..end
rand(start..=end)INTgenerates a random number within the inclusive range start..=end
rand_float()FLOATfloatgenerates a random floating-point number between 0.0 and 1.0 (exclusive)
rand_decimal()Decimaldecimalgenerates a random decimal number
rand_bool()boolgenerates a random boolean
rand_bool(p)boolfloatgenerates a random boolean with the probability p of being true
Array::shuffle()arrayshuffles the elements in the Rhai array
Array::sample()Dynamicarraycopies a random element from the Rhai array
Array::sample(n)Arrayarraycopies a non-repeating random sample of elements from the Rhai array


Package for random number generation, sampling and shuffling.