mlua_mathlib/lib.rs
1#![deny(unsafe_code)]
2//! Math library for mlua — RNG, distributions, and descriptive statistics.
3//!
4//! Provides math functions that are impractical or numerically unstable
5//! to implement in pure Lua: distribution sampling with proper algorithms,
6//! independent seeded RNG instances, and numerically stable statistics.
7//!
8//! # Quick start
9//!
10//! ```rust,no_run
11//! use mlua::prelude::*;
12//!
13//! let lua = Lua::new();
14//! let math = mlua_mathlib::module(&lua).unwrap();
15//! lua.globals().set("math", math).unwrap();
16//!
17//! lua.load(r#"
18//! local rng = math.rng_create(42)
19//! print(math.normal_sample(rng, 0.0, 1.0))
20//! print(math.mean({1, 2, 3, 4, 5}))
21//! "#).exec().unwrap();
22//! ```
23
24mod cdf;
25mod distribution;
26mod rng;
27mod special;
28mod stats;
29
30use mlua::prelude::*;
31
32/// Create the math module table with all functions registered.
33///
34/// # Examples
35///
36/// ```rust,no_run
37/// use mlua::prelude::*;
38///
39/// let lua = Lua::new();
40/// let math = mlua_mathlib::module(&lua).unwrap();
41/// lua.globals().set("math", math).unwrap();
42///
43/// // RNG
44/// lua.load("local rng = math.rng_create(42); print(math.rng_float(rng))").exec().unwrap();
45///
46/// // Statistics
47/// let mean: f64 = lua.load("return math.mean({1, 2, 3, 4, 5})").eval().unwrap();
48/// assert!((mean - 3.0).abs() < 1e-10);
49/// ```
50pub fn module(lua: &Lua) -> LuaResult<LuaTable> {
51 let t = lua.create_table()?;
52
53 rng::register(lua, &t)?;
54 distribution::register(lua, &t)?;
55 stats::register(lua, &t)?;
56 special::register(lua, &t)?;
57 cdf::register(lua, &t)?;
58
59 Ok(t)
60}