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 hypothesis;
27mod information;
28mod ranking;
29mod rng;
30mod special;
31mod stats;
32
33use mlua::prelude::*;
34
35/// Create the math module table with all functions registered.
36///
37/// # Examples
38///
39/// ```rust,no_run
40/// use mlua::prelude::*;
41///
42/// let lua = Lua::new();
43/// let math = mlua_mathlib::module(&lua).unwrap();
44/// lua.globals().set("math", math).unwrap();
45///
46/// // RNG
47/// lua.load("local rng = math.rng_create(42); print(math.rng_float(rng))").exec().unwrap();
48///
49/// // Statistics
50/// let mean: f64 = lua.load("return math.mean({1, 2, 3, 4, 5})").eval().unwrap();
51/// assert!((mean - 3.0).abs() < 1e-10);
52/// ```
53pub fn module(lua: &Lua) -> LuaResult<LuaTable> {
54 let t = lua.create_table()?;
55
56 rng::register(lua, &t)?;
57 distribution::register(lua, &t)?;
58 stats::register(lua, &t)?;
59 ranking::register(lua, &t)?;
60 hypothesis::register(lua, &t)?;
61 information::register(lua, &t)?;
62 special::register(lua, &t)?;
63 cdf::register(lua, &t)?;
64
65 Ok(t)
66}