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.
Usage
Cargo.toml
[dependencies]
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!
a.shuffle();
// Now the array is shuffled randomly!
print(a);
// Sample a random value from the array
print(a.sample());
// Or sample multiple values
print(a.sample(3));
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
engine.register_global_module(RandomPackage::new().as_shared_module());
// 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);
}
Features
Feature | Default | Description |
---|---|---|
float | Enabled | provides random floating-point number generation |
array | Enabled | provides methods for Rhai arrays |
API
The following functions are defined in this package:
Function | Return type | Feature | Description |
---|---|---|---|
rand() | INT | generates a random number | |
rand(start..end) | INT | generates a random number within the exclusive range start..end | |
rand(start..=end) | INT | generates a random number within the inclusive range start..=end | |
rand_float() | FLOAT | float | generates a random floating-point number between 0.0 and 1.0 (exclusive) |
rand_bool() | bool | generates a random boolean | |
rand_bool(p) | bool | float | generates a random boolean with the probability p of being true |
Array::shuffle() | array | shuffles the elements 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 |
Structs
Package for random number generation, sampling and shuffling.