### Registering Binary Metamethods Source: https://docs.rs/mlua/latest/mlua/derive.UserData.html Example of registering a binary metamethod without a receiver. ```rust #[mlua::userdata_impl] impl Vec2 { // No receiver: both operands are declared and passed directly by Lua. #[lua(meta, infallible, name = "__add")] fn add(a: &Vec2, b: &Vec2) -> Vec2 { ... } } ``` -------------------------------- ### Partitioning a slice Source: https://docs.rs/mlua/latest/mlua/struct.BString.html Examples demonstrating the use of partition_point to find the index where a predicate changes from true to false. ```rust assert_eq!(i, 4); assert!(v[..i].iter().all(|&x| x < 5)); assert!(v[i..].iter().all(|&x| !(x < 5))); ``` ```rust let a = [2, 4, 8]; assert_eq!(a.partition_point(|x| x < &100), a.len()); let a: [i32; 0] = []; assert_eq!(a.partition_point(|x| x < &100), 0); ``` ```rust let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]; let num = 42; let idx = s.partition_point(|&x| x <= num); s.insert(idx, num); assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); ``` -------------------------------- ### Demonstrate rsplit usage Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Examples of splitting strings in reverse order using various pattern types. ```rust let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect(); assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]); let v: Vec<&str> = "".rsplit('X').collect(); assert_eq!(v, [""]); let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect(); assert_eq!(v, ["leopard", "tiger", "", "lion"]); let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect(); assert_eq!(v, ["leopard", "tiger", "lion"]); ``` ```rust let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect(); assert_eq!(v, ["ghi", "def", "abc"]); ``` -------------------------------- ### Manual extract_if Implementation Source: https://docs.rs/mlua/latest/mlua/struct.MultiValue.html?search= An example showing the manual logic equivalent to the experimental extract_if method. ```rust #![feature(vec_deque_extract_if)] let mut i = range.start; let end_items = deq.len() - range.end; while i < deq.len() - end_items { if some_predicate(&mut deq[i]) { let val = deq.remove(i).unwrap(); // your code here } else { i += 1; } } ``` -------------------------------- ### Implementing UserData for a Struct Source: https://docs.rs/mlua/latest/mlua/derive.UserData.html Example showing how to derive UserData and use userdata_impl to expose fields and methods. ```rust use mlua::{Lua, Result, UserData}; #[derive(UserData)] struct Rectangle { length: u32, width: u32, } #[mlua::userdata_impl] impl Rectangle { #[lua(infallible)] fn new(length: u32, width: u32) -> Self { Self { length, width } } #[lua(getter, name = "area", infallible)] fn calculate_area(&self) -> u32 { self.length * self.width } fn diagonal(&self) -> Result { Ok(((self.length.pow(2) + self.width.pow(2)) as f64).sqrt()) } } ``` -------------------------------- ### Negative example of split behavior Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Illustrates what split does not provide compared to other methods. ```rust assert_eq!(d, &["a", "b", "c"]); ``` -------------------------------- ### IntoLua Implementation for Primitive Types Source: https://docs.rs/mlua/latest/mlua/trait.IntoLua.html?search=u32+-%3E+bool Examples of the into_lua method implementation for various primitive types. ```rust fn into_lua(self, lua: &Lua) -> Result ``` ```rust fn into_lua(self, _: &Lua) -> Result ``` -------------------------------- ### IntoLua Implementation for Collections and Complex Types Source: https://docs.rs/mlua/latest/mlua/trait.IntoLua.html?search=u32+-%3E+bool Examples of the into_lua method implementation for collections and other complex types. ```rust fn into_lua(self, lua: &Lua) -> Result ``` -------------------------------- ### get Source: https://docs.rs/mlua/latest/mlua/userdata/struct.UserDataMetatable.html Gets the value associated with a key from the metatable. Returns the Nil value if the key is not found. Access to restricted metamethods like __gc or __metatable will cause an error. ```APIDOC ## pub fn get(&self, key: impl AsRef) -> Result ### Description Gets the value associated to `key` from the metatable. If no value is associated to `key`, returns the `Nil` value. Access to restricted metamethods such as `__gc` or `__metatable` will cause an error. ``` -------------------------------- ### Lua Initialization Methods Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search= Methods for creating and configuring a new Lua VM instance. ```APIDOC ## Lua::new() Creates a new Lua state and loads the safe subset of the standard libraries. ## Lua::unsafe_new() Creates a new Lua state and loads all the standard libraries. Note: This is an unsafe operation. ## Lua::new_with(libs: StdLib, options: LuaOptions) Creates a new Lua state and loads a specified safe subset of standard libraries. ## Lua::unsafe_new_with(libs: StdLib, options: LuaOptions) Creates a new Lua state and loads a specified subset of standard libraries. Note: This is an unsafe operation. ``` -------------------------------- ### app_data_mut Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=u32+-%3E+bool Gets a mutable reference to application data. ```APIDOC ## pub fn app_data_mut(&self) -> Option> ### Description Gets a mutable reference to an application data object stored by `Lua::set_app_data` of type `T`. Panics if the data object is currently borrowed. ``` -------------------------------- ### JitOptions::new Source: https://docs.rs/mlua/latest/mlua/state/struct.JitOptions.html Creates a new instance of JitOptions with default settings. ```APIDOC ## pub const fn new() -> Self ### Description Creates default JIT options. ### Returns - **Self** - A new instance of JitOptions. ``` -------------------------------- ### Create and Configure JitOptions Source: https://docs.rs/mlua/latest/mlua/state/struct.JitOptions.html?search= Methods for initializing and configuring JIT options. ```rust pub const fn new() -> Self ``` ```rust pub const fn inliner(self, enabled: bool) -> Self ``` -------------------------------- ### app_data_ref Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=u32+-%3E+bool Gets an immutable reference to application data. ```APIDOC ## pub fn app_data_ref(&self) -> Option> ### Description Gets a reference to an application data object stored by `Lua::set_app_data` of type `T`. Panics if the data object is currently mutably borrowed. ``` -------------------------------- ### Options::new Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Options.html Creates a new instance of Options with default settings. ```APIDOC ### pub const fn new() -> Self Returns a new instance of `Options` with default parameters. ``` -------------------------------- ### app_data_mut Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a mutable reference to application data. ```APIDOC ## pub fn app_data_mut(&self) -> Option> ### Description Gets a mutable reference to an application data object stored by `Lua::set_app_data` of type `T`. Panics if the data is currently borrowed. ``` -------------------------------- ### app_data_ref Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets an immutable reference to application data. ```APIDOC ## pub fn app_data_ref(&self) -> Option> ### Description Gets a reference to an application data object stored by `Lua::set_app_data` of type `T`. Panics if the data is currently mutably borrowed. ``` -------------------------------- ### Options::new Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Options.html?search=u32+-%3E+bool Creates a new instance of the Options configuration struct with default settings. ```APIDOC ## pub const fn new() -> Self ### Description Returns a new instance of `Options` with default parameters. ``` -------------------------------- ### registry_value Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a value from the Lua registry by its RegistryKey. ```APIDOC ## pub fn registry_value(&self, key: &RegistryKey) -> Result ### Description Get a value from the Lua registry by its `RegistryKey`. ``` -------------------------------- ### Lua VM Methods Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search= Methods for configuring the Lua environment and creating Lua-compatible objects from Rust. ```APIDOC ## pub fn set_compiler(&self, compiler: Compiler) ### Description Sets a default Luau compiler with custom options. This compiler is used for loading all Lua chunks, including those loaded via `require`. ## pub fn enable_jit(&self, enable: bool) ### Description Toggles JIT compilation mode for new chunks of code. By default, JIT is enabled. ## pub fn load<'a>(&self, chunk: impl AsChunk + 'a) -> Chunk<'a> ### Description Returns a `Chunk` builder for the provided source code. The code is not parsed until `Chunk::exec` or a similar method is called. ## pub fn create_string(&self, s: impl AsRef<[u8]>) -> Result ### Description Creates and returns an interned Lua string from the provided byte slice or string. ## pub fn create_table(&self) -> Result ### Description Creates and returns a new empty table. ## pub fn create_table_with_capacity(&self, narr: usize, nrec: usize) -> Result
### Description Creates and returns a new empty table with preallocated capacity for sequence elements (`narr`) and other elements (`nrec`). ## pub fn create_function(&self, func: F) -> Result ### Description Wraps a Rust function or closure into a callable Lua function handle. Errors returned by the Rust function are raised as Lua errors. ``` -------------------------------- ### starts_with Source: https://docs.rs/mlua/latest/mlua/struct.Variadic.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Checks if the slice starts with the given needle. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns true if needle is a prefix of the slice or equal to the slice. ``` -------------------------------- ### Lua::new Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=u32+-%3E+bool Creates a new Lua state and loads the safe subset of the standard libraries. ```APIDOC ## pub fn new() ### Description Creates a new Lua state and loads the safe subset of the standard libraries. This state provides safety guarantees and prevents loading unsafe standard libraries or C modules. ### Returns - **Lua** - A new instance of the Lua VM. ``` -------------------------------- ### Lua::new_with Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Lua state with specific standard library flags and options. ```APIDOC ## Lua::new_with(libs: StdLib, options: LuaOptions) ### Description Creates a new Lua state and loads the specified safe subset of the standard libraries defined by the `libs` flags. ``` -------------------------------- ### starts_with Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html?search=std%3A%3Avec Checks if the slice starts with the given prefix. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ``` -------------------------------- ### enable_jit Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html Toggles JIT compilation mode for new chunks of code. ```APIDOC ## pub fn enable_jit(&self, enable: bool) ### Description Toggles JIT compilation mode for new chunks of code. By default JIT is enabled. Changing this option does not have any effect on already loaded functions. ``` -------------------------------- ### as_array Source: https://docs.rs/mlua/latest/mlua/struct.BString.html?search=std%3A%3Avec Gets a reference to the underlying array if the length matches. ```APIDOC ## pub fn as_array(&self) -> Option<&[T; N]> ### Description Gets a reference to the underlying array. Returns None if N is not exactly equal to the length of the slice. ``` -------------------------------- ### Get slice length Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html Returns the number of elements in the slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Lua VM Configuration Methods Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=u32+-%3E+bool Methods for configuring the Lua VM, including compiler settings and JIT compilation. ```APIDOC ## set_compiler(compiler: Compiler) Sets a default Luau compiler with custom options. Available on `luau` feature. ## enable_jit(enable: bool) Toggles JIT compilation mode for new chunks. Available on `luau-jit` feature. ## set_jit_options(options: JitOptions) Configures JIT options for the Lua VM. Available on `luau-jit` feature. ``` -------------------------------- ### Get vector length Source: https://docs.rs/mlua/latest/mlua/struct.BString.html Returns the number of elements currently in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Accessing Elements with get Source: https://docs.rs/mlua/latest/mlua/struct.MultiValue.html?search= Retrieving a reference to an element at a specific index. ```rust use std::collections::VecDeque; let mut buf = VecDeque::new(); buf.push_back(3); buf.push_back(4); buf.push_back(5); buf.push_back(6); assert_eq!(buf.get(1), Some(&4)); ``` -------------------------------- ### Create new Compiler instance Source: https://docs.rs/mlua/latest/mlua/chunk/struct.Compiler.html?search= Initializes a new Luau compiler instance with default options. ```rust pub const fn new() -> Self ``` -------------------------------- ### named_registry_value Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Gets a value from the Lua registry based on a string key. ```APIDOC ## pub fn named_registry_value(&self, key: &str) -> Result ### Description Get a value from the Lua registry based on a string key. ``` -------------------------------- ### LuaOptions::new Source: https://docs.rs/mlua/latest/mlua/struct.LuaOptions.html?search= Creates a new instance of LuaOptions with default parameters. ```APIDOC ## pub const fn new() -> Self ### Description Returns a new instance of `LuaOptions` with default parameters. ### Signature `pub const fn new() -> Self` ``` -------------------------------- ### LuaOptions::new Source: https://docs.rs/mlua/latest/mlua/struct.LuaOptions.html?search=std%3A%3Avec Creates a new instance of LuaOptions with default parameters. ```APIDOC ## pub const fn new() -> Self ### Description Returns a new instance of `LuaOptions` with default parameters. ``` -------------------------------- ### inspect_stack Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search= Gets information about the interpreter runtime stack at the given level. ```APIDOC ## pub fn inspect_stack( &self, level: usize, f: impl FnOnce(&Debug<'_>) -> R, ) -> Option ### Description Gets information about the interpreter runtime stack at the given level. Level 0 is the current running function. ``` -------------------------------- ### Trim start matches Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Removes prefixes that match a provided pattern. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); ``` -------------------------------- ### enable_jit Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search= Toggles JIT compilation mode for new chunks of code. Available only with the 'luau-jit' feature. ```APIDOC ## pub fn enable_jit(&self, enable: bool) ### Description Toggles JIT compilation mode for new chunks of code. By default JIT is enabled. Changing this option does not have any effect on already loaded functions. ### Parameters - **enable** (bool) - Required - Whether to enable JIT. ``` -------------------------------- ### Compiler::new Source: https://docs.rs/mlua/latest/mlua/chunk/struct.Compiler.html?search=u32+-%3E+bool Creates a new instance of the Luau compiler with default options. ```APIDOC ## pub const fn new() -> Self ### Description Creates a Luau compiler instance with default options. ``` -------------------------------- ### Trim start of string Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Removes leading whitespace from a string slice. ```rust let s = " עברית "; assert!(Some('ע') == s.trim_start().chars().next()); ``` -------------------------------- ### Check string prefix Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Verifies if the string starts with a specific pattern. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` -------------------------------- ### Get last element Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html Returns the last element of the slice, or None if it is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&30), v.last()); let w: &[i32] = &[]; assert_eq!(None, w.last()); ``` -------------------------------- ### Get first element Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html Returns the first element of the slice, or None if it is empty. ```rust let v = [10, 40, 30]; assert_eq!(Some(&10), v.first()); let w: &[i32] = &[]; assert_eq!(None, w.first()); ``` -------------------------------- ### Create and resume a Lua thread Source: https://docs.rs/mlua/latest/mlua/thread/index.html Demonstrates creating a coroutine using Lua::create_thread and driving its execution via Thread::resume. ```rust let lua = Lua::new(); let thread: Thread = lua.load(r#" coroutine.create(function(a, b) coroutine.yield(a + b) return a * b end) "#).eval()?; assert_eq!(thread.resume::((3, 4))?, 7); assert_eq!(thread.resume::(())?, 12); ``` -------------------------------- ### environment / set_environment Source: https://docs.rs/mlua/latest/mlua/function/struct.Function.html?search=u32+-%3E+bool Methods to get or set the environment table for the Lua function. ```APIDOC ## pub fn environment(&self) -> Option
### Description Returns the environment of the Lua function. By default Lua functions share a global environment. ## pub fn set_environment(&self, env: Table) -> Result ### Description Sets the environment of the Lua function. Returns `true` if environment successfully changed, `false` otherwise. ``` -------------------------------- ### Lua VM Management Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for interacting with an existing Lua VM instance. ```APIDOC ## Lua::load_std_libs(libs: StdLib) ### Description Loads the specified subset of the standard libraries into an existing Lua state. ## Lua::register_module(modname: &str, value: impl IntoLua) ### Description Registers a module into an existing Lua state. The provided value will be returned when the module is required. ## Lua::preload_module(modname: &str, func: Function) ### Description Preloads a module into an existing Lua state using a loader function. (Available on non-luau features). ``` -------------------------------- ### create_table Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for creating and initializing Lua tables. ```APIDOC ## pub fn create_table(&self) -> Result
### Description Creates and returns a new empty table. ## pub fn create_table_with_capacity(&self, narr: usize, nrec: usize) -> Result
### Description Creates and returns a new empty table, with the specified capacity hints for sequence and record elements. ### Parameters - **narr** (usize) - Required - Hint for sequence elements. - **nrec** (usize) - Required - Hint for other elements. ``` -------------------------------- ### environment management Source: https://docs.rs/mlua/latest/mlua/function/struct.Function.html?search=std%3A%3Avec Methods to get or set the environment table of the Lua function. ```APIDOC ## pub fn environment(&self) -> Option
### Description Returns the environment of the Lua function. Returns `None` for Rust/C functions. ## pub fn set_environment(&self, env: Table) -> Result ### Description Sets the environment of the Lua function. Returns `true` if successful, `false` otherwise. ``` -------------------------------- ### Serializer::new Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Serializer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Lua Serializer instance with default options. ```APIDOC ## pub fn new(lua: &'a Lua) -> Self ### Description Creates a new Lua Serializer with default options. ### Parameters - **lua** (&'a Lua) - Required - A reference to the Lua state. ``` -------------------------------- ### Check prefix and suffix Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Verifies if a string starts or ends with a specific pattern. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` ```rust let bananas = "bananas"; assert!(bananas.ends_with("anas")); assert!(!bananas.ends_with("nana")); ``` -------------------------------- ### Serializer::new Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Serializer.html Creates a new Lua Serializer instance with default options. ```APIDOC ## pub fn new(lua: &'a Lua) -> Self ### Description Creates a new Lua Serializer with default options. ### Parameters - **lua** (&'a Lua) - Required - The Lua context to use for serialization. ``` -------------------------------- ### Retrieve match indices Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Returns an iterator over disjoint matches and their starting indices. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Object Creation Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for creating Lua strings, buffers, and tables. ```APIDOC ## create_string(s: impl AsRef<[u8]>) Creates and returns an interned Lua string. ## create_external_string(s: impl Into>) Creates an external Lua string where memory is managed by Rust. Available on crate feature `lua55`. ## create_buffer(data: impl AsRef<[u8]>) Creates a Luau buffer object from a byte slice. Available on crate feature `luau`. ## create_buffer_with_capacity(size: usize) Creates a Luau buffer object with the specified size (up to 1GB). Available on crate feature `luau`. ## create_table() Creates and returns a new empty table. ## create_table_with_capacity(narr: usize, nrec: usize) Creates a new empty table with preallocated capacity hints. ## create_table_from(iter: impl IntoIterator) Creates a table and fills it with values from an iterator. ## create_sequence_from(iter: impl IntoIterator) Creates a table from an iterator of values, using 1-based integer keys. ``` -------------------------------- ### starts_with

(pat: P) Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Checks if the string starts with the given pattern. ```APIDOC ## pub fn starts_with

(&self, pat: P) -> bool ### Description Returns `true` if the given pattern matches a prefix of this string slice. ``` -------------------------------- ### Module and Library Management Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search= Methods for loading standard libraries and registering custom modules. ```APIDOC ## Lua::load_std_libs(libs: StdLib) Loads the specified subset of the standard libraries into an existing Lua state. ## Lua::register_module(modname: &str, value: impl IntoLua) Registers a module into an existing Lua state. The provided value is returned when the module is required. ## Lua::preload_module(modname: &str, func: Function) Preloads a module into an existing Lua state using a loader function (Available on non-luau features). ``` -------------------------------- ### Lua VM Methods Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search=std%3A%3Avec Methods for managing Lua VM state, creating data structures, and exposing Rust functions to Lua. ```APIDOC ## pub fn set_compiler(&self, compiler: Compiler) Sets a default Luau compiler with custom options. Available on crate feature `luau`. ## pub fn enable_jit(&self, enable: bool) Toggles JIT compilation mode for new chunks. Available on crate feature `luau-jit`. ## pub fn load<'a>(&self, chunk: impl AsChunk + 'a) -> Chunk<'a> Returns a `Chunk` builder for the provided source code. ## pub fn create_string(&self, s: impl AsRef<[u8]>) -> Result Creates and returns an interned Lua string. ## pub fn create_table(&self) -> Result

Creates and returns a new empty table. ## pub fn create_table_with_capacity(&self, narr: usize, nrec: usize) -> Result
Creates and returns a new empty table with preallocated capacity for sequence and record elements. ## pub fn create_function(&self, func: F) -> Result Wraps a Rust function or closure, creating a callable Lua function handle. ``` -------------------------------- ### as_mut_array Source: https://docs.rs/mlua/latest/mlua/struct.BString.html?search=std%3A%3Avec Gets a mutable reference to the slice’s underlying array if the length matches. ```APIDOC ## pub fn as_mut_array(&mut self) -> Option<&mut [T; N]> ### Description Gets a mutable reference to the slice’s underlying array. Returns None if N is not exactly equal to the length of the slice. ``` -------------------------------- ### Module Management Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search= Methods for registering and preloading modules within the Lua state. ```APIDOC ## Lua::register_module(modname: &str, value: impl IntoLua) Registers a module into the Lua state using the specified value. ## Lua::preload_module(modname: &str, func: Function) Preloads a module into the Lua state using a loader function (non-luau feature). ``` -------------------------------- ### Get Global Value Source: https://docs.rs/mlua/latest/mlua/struct.Table.html?search=u32+-%3E+bool Retrieve a value from the global table, such as the Lua interpreter version. ```rust let globals = lua.globals(); let version: String = globals.get("_VERSION")?; println!("Lua version: {}", version); ``` -------------------------------- ### Get VecDeque capacity Source: https://docs.rs/mlua/latest/mlua/struct.MultiValue.html?search= Returns the number of elements the deque can hold without reallocating. ```rust use std::collections::VecDeque; let buf: VecDeque = VecDeque::with_capacity(10); assert!(buf.capacity() >= 10); ``` -------------------------------- ### AnyUserData Constructors Source: https://docs.rs/mlua/latest/mlua/userdata/struct.AnyUserData.html?search=std%3A%3Avec Static methods for creating AnyUserData instances. ```APIDOC ## pub fn wrap(data: T) -> impl IntoLua Wraps any Rust type, returning an opaque type that implements IntoLua trait. ## pub fn wrap_ser(data: T) -> impl IntoLua Wraps any Rust type that implements Serialize, returning an opaque type that implements IntoLua trait. ``` -------------------------------- ### Trim start matches with a pattern Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedStr.html Removes leading characters that match the provided pattern. ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Serializer::new_with_options Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Serializer.html Creates a new Lua Serializer instance with custom configuration options. ```APIDOC ## pub fn new_with_options(lua: &'a Lua, options: Options) -> Self ### Description Creates a new Lua Serializer with custom options. ### Parameters - **lua** (&'a Lua) - Required - The Lua context to use for serialization. - **options** (Options) - Required - Custom serialization options. ``` -------------------------------- ### rsplit Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html?search= Returns an iterator over subslices separated by elements that match a predicate, starting from the end. ```APIDOC ## pub fn rsplit(&self, pred: F) -> RSplit<'_, T, F> ### Description Returns an iterator over subslices separated by elements that match `pred`, starting at the end of the slice and working backwards. The matched element is not contained in the subslices. ``` -------------------------------- ### rchunks Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice. ```APIDOC ## pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T> ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. If `chunk_size` does not divide the length of the slice, then the last chunk will not have length `chunk_size`. ### Parameters - **chunk_size** (usize) - Required - The size of each chunk. Panics if zero. ``` -------------------------------- ### Serializer::new_with_options Source: https://docs.rs/mlua/latest/mlua/serde/ser/struct.Serializer.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new Lua Serializer instance with custom configuration options. ```APIDOC ## pub fn new_with_options(lua: &'a Lua, options: Options) -> Self ### Description Creates a new Lua Serializer with custom options. ### Parameters - **lua** (&'a Lua) - Required - A reference to the Lua state. - **options** (Options) - Required - Custom serialization options. ``` -------------------------------- ### Registering Metamethods Source: https://docs.rs/mlua/latest/mlua/derive.UserData.html Annotating methods with meta allows them to be registered as Lua metamethods. ```rust #[mlua::userdata_impl] impl MyType { #[lua(meta, infallible)] fn __add(&self, other: &Self) -> Self { ... } #[lua(meta, name = "__call", infallible)] fn construct(this: mlua::AnyUserData, value: u32) -> Self { ... } } ``` -------------------------------- ### Trim ASCII whitespace from start Source: https://docs.rs/mlua/latest/mlua/string/struct.BorrowedBytes.html Removes leading ASCII whitespace bytes from the slice. ```rust assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n"); assert_eq!(b" ".trim_ascii_start(), b""); assert_eq!(b"".trim_ascii_start(), b""); ``` -------------------------------- ### create_table Source: https://docs.rs/mlua/latest/mlua/state/struct.Lua.html?search= Creates and returns a new empty table. ```APIDOC ## pub fn create_table(&self) -> Result
### Description Creates and returns a new empty table. ``` -------------------------------- ### Copying Result Contents Source: https://docs.rs/mlua/latest/mlua/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Examples of copying or cloning the contents of a Result containing a reference. ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let val = 12; let x: Result<&i32, i32> = Ok(&val); assert_eq!(x, Ok(&12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let copied = x.copied(); assert_eq!(copied, Ok(12)); ``` ```rust let mut val = 12; let x: Result<&mut i32, i32> = Ok(&mut val); assert_eq!(x, Ok(&mut 12)); let cloned = x.cloned(); assert_eq!(cloned, Ok(12)); ``` -------------------------------- ### pub fn sandbox(&self) -> Result<()> Source: https://docs.rs/mlua/latest/mlua/struct.Thread.html?search= Enables sandbox mode on the thread by replacing the global environment table with a local proxy. This method is only available when the 'luau' crate feature is enabled. ```APIDOC ## pub fn sandbox(&self) -> Result<()> ### Description Enables sandbox mode on this thread. Under the hood, it replaces the global environment table with a new table that performs writes locally and proxies reads to the caller's global environment. ### Requirements - Crate feature: `luau` ``` -------------------------------- ### get Source: https://docs.rs/mlua/latest/mlua/struct.Variadic.html Returns a reference to an element or subslice depending on the type of index. Returns None if out of bounds. ```APIDOC ## get ### Description Returns a reference to an element or subslice depending on the type of index. If given a position, returns a reference to the element at that position or None if out of bounds. If given a range, returns the subslice corresponding to that range, or None if out of bounds. ``` -------------------------------- ### pub fn sandbox(&self, enabled: bool) -> Result<()> Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search=std%3A%3Avec Enables or disables sandbox mode on the Lua instance. Requires the `luau` feature. ```APIDOC ## pub fn sandbox(&self, enabled: bool) -> Result<()> ### Description Enables or disables sandbox mode. When enabled, libraries, metatables, and globals are set to read-only, and a local environment table is used. ### Parameters - **enabled** (bool) - Required - Whether to enable or disable sandbox mode. ``` -------------------------------- ### Get reference to Result Source: https://docs.rs/mlua/latest/mlua/type.Result.html?search=u32+-%3E+bool Use as_ref() to create a Result containing references to the original values. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Get last chunk of slice Source: https://docs.rs/mlua/latest/mlua/struct.BString.html Retrieves an array reference to the last N items in the slice. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### LuaSerdeExt Methods Source: https://docs.rs/mlua/latest/mlua/struct.Lua.html?search=u32+-%3E+bool Methods for Serde integration, available when the 'serde' feature is enabled. ```APIDOC ## LuaSerdeExt Methods ### null Returns a special value (lightuserdata) to encode/decode optional (none) values. ### array_metatable Returns a metatable attachable to a Lua table to systematically encode it as an Array instead of a Map. ### to_value Converts a serializable type `T` into a `Value` instance. ### to_value_with Converts a serializable type `T` into a `Value` instance using specific `Options`. ### from_value Deserializes a `Value` into any serde deserializable object `T`. ### from_value_with Deserializes a `Value` into any serde deserializable object `T` using specific `Options`. ```