rhai-rand: Random Number Generation, Shuffling and Sampling

rhai-rand is an independent Rhai package that provides:

  • random number generation using the rand crate
  • array shuffling and sampling

On crates.io: rhai-rand

On GitHub: rhaiscript/rhai-rand

Package name: RandomPackage

Dependency

Cargo.toml:

[dependencies]
rhai = "{{version}}"
rhai-rand = "0.1"       # use rhai-rand crate

Load Package into Engine

use rhai::Engine;
use rhai::packages::Package;    // needed for 'as_shared_module'
use rhai_rand::RandomPackage;

let mut engine = Engine::new();

// Create new 'RandomPackage' instance
let random = RandomPackage::new();

// Load the package
engine.register_global_module(random.as_shared_module());

Features

FeatureDescriptionDefault?Should not be used with Rhai feature
floatenables random floating-point number generationyesno_float
arrayenables methods for arraysyesno_index
metadataenables functions metadata (turns on metadata in Rhai)no

Example – working with no_float in Rhai

Cargo.toml:

[dependencies]
# Rhai is set for 'no_float', meaning no floating-point support
rhai = { version="{{version}}", features = ["no_float"] }

# Use 'default-features = false' to clear defaults, then only add 'array'
rhai-rand = { version="0.1", default-features = false, features = ["array"] }

Package Functions

The following functions are defined.

FunctionReturn typeFeatureDescription
rand()INTgenerates a random integer number
rand(start..end)INTgenerates a random integer number within the exclusive range start..end
rand(start..=end)INTgenerates a random integer number within the inclusive range start..=end
rand(start, end)INTgenerates a random integer number within the inclusive range start..=end
rand_float()FLOATfloatgenerates a random floating-point number between 0.0 and 1.0 (exclusive)
rand_float(start, end)FLOATfloatgenerates a random floating-point number within the inclusive range start..=end
rand_decimal()Decimalgenerates a random decimal number
rand_decimal(start, end)Decimalgenerates a random decimal number within the inclusive range start..=end
rand_bool()boolgenerates a random boolean
rand_bool(p)boolfloatgenerates a random boolean with the probability p of being true

Arrays

The following methods are defined for arrays (requires the array feature).

MethodParameter(s)Return typeDescription
shufflenoneshuffles the items in the array
samplenoneDynamicreturns a random item from the array
samplenumber of items to sample (empty if ≤ 0, all if ≥ length)Arrayreturns a non-repeating shuffled random sample of items from the array