rhai_rand/lib.rs
1//! # `rhai-rand` - Rhai Functions for Random Number Generation
2//!
3//! `rhai-rand` is a [Rhai] package to provide random number generation using the [`rand`] crate.
4//!
5//!
6//! ## Usage
7//!
8//!
9//! ### `Cargo.toml`
10//!
11//! ```toml
12//! [dependencies]
13//! rhai-rand = "0.1"
14//! ```
15//!
16//! ### [Rhai] script
17//!
18//! ```js
19//! // Create random boolean
20//! let decision = rand_bool();
21//!
22//! if decision {
23//! // Create random number
24//! let random_value = rand();
25//! print(`Random number = ${random_value}`);
26//! } else {
27//! print("Fixed number = 42");
28//! }
29//!
30//! // Create array
31//! let a = [1, 2, 3, 4, 5];
32//!
33//! // Shuffle it!
34//! a.shuffle();
35//!
36//! // Now the array is shuffled randomly!
37//! print(a);
38//!
39//! // Sample a random value from the array
40//! print(a.sample());
41//!
42//! // Or sample multiple values
43//! print(a.sample(3));
44//! ```
45//!
46//! ### Rust source
47//!
48//! ```rust
49//! # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
50//! use rhai::Engine;
51//! use rhai::packages::Package;
52//!
53//! use rhai_rand::RandomPackage;
54//!
55//! // Create Rhai scripting engine
56//! let mut engine = Engine::new();
57//!
58//! // Create random number package and add the package into the engine
59//! engine.register_global_module(RandomPackage::new().as_shared_module());
60//!
61//! // Print 10 random numbers, each of which between 0-100!
62//! for _ in 0..10 {
63//! let value = engine.eval::<i64>("rand(0..=100)")?;
64//!
65//! println!("Random number = {}", value);
66//! }
67//! # Ok(())
68//! # }
69//! ```
70//!
71//! ## Features
72//!
73#![cfg_attr(feature = "document-features", doc = document_features::document_features!(feature_label = "<span id=\"feature-{feature}\">**`{feature}`**</span>"))]
74//!
75//! ## API
76//!
77//! The following functions are defined in this package:
78//!
79#![doc = include_str!(concat!(env!("OUT_DIR"), "/rhai-rand-docs.md"))]
80//!
81//! [Rhai]: https://rhai.rs
82//! [`rand`]: https://crates.io/crates/rand
83//! [`Decimal`]: https://crates.io/crates/rust_decimal
84
85use rhai::def_package;
86use rhai::plugin::*;
87
88#[cfg(feature = "array")]
89mod array;
90mod rand;
91
92def_package! {
93 /// Package for random number generation, sampling and shuffling.
94 pub RandomPackage(lib) {
95 combine_with_exported_module!(lib, "rand", rand::rand_functions);
96
97 #[cfg(feature = "array")]
98 combine_with_exported_module!(lib, "array", array::array_functions);
99 }
100}