mlua_codemp_patch/
lib.rs

1//! # High-level bindings to Lua
2//!
3//! The `mlua` crate provides safe high-level bindings to the [Lua programming language].
4//!
5//! # The `Lua` object
6//!
7//! The main type exported by this library is the [`Lua`] struct. In addition to methods for
8//! [executing] Lua chunks or [evaluating] Lua expressions, it provides methods for creating Lua
9//! values and accessing the table of [globals].
10//!
11//! # Converting data
12//!
13//! The [`IntoLua`] and [`FromLua`] traits allow conversion from Rust types to Lua values and vice
14//! versa. They are implemented for many data structures found in Rust's standard library.
15//!
16//! For more general conversions, the [`IntoLuaMulti`] and [`FromLuaMulti`] traits allow converting
17//! between Rust types and *any number* of Lua values.
18//!
19//! Most code in `mlua` is generic over implementors of those traits, so in most places the normal
20//! Rust data structures are accepted without having to write any boilerplate.
21//!
22//! # Custom Userdata
23//!
24//! The [`UserData`] trait can be implemented by user-defined types to make them available to Lua.
25//! Methods and operators to be used from Lua can be added using the [`UserDataMethods`] API.
26//! Fields are supported using the [`UserDataFields`] API.
27//!
28//! # Serde support
29//!
30//! The [`LuaSerdeExt`] trait implemented for [`Lua`] allows conversion from Rust types to Lua
31//! values and vice versa using serde. Any user defined data type that implements
32//! [`serde::Serialize`] or [`serde::Deserialize`] can be converted.
33//! For convenience, additional functionality to handle `NULL` values and arrays is provided.
34//!
35//! The [`Value`] enum implements [`serde::Serialize`] trait to support serializing Lua values
36//! (including [`UserData`]) into Rust values.
37//!
38//! Requires `feature = "serialize"`.
39//!
40//! # Async/await support
41//!
42//! The [`create_async_function`] allows creating non-blocking functions that returns [`Future`].
43//! Lua code with async capabilities can be executed by [`call_async`] family of functions or
44//! polling [`AsyncThread`] using any runtime (eg. Tokio).
45//!
46//! Requires `feature = "async"`.
47//!
48//! # `Send` requirement
49//! By default `mlua` is `!Send`. This can be changed by enabling `feature = "send"` that adds
50//! `Send` requirement to [`Function`]s and [`UserData`].
51//!
52//! [Lua programming language]: https://www.lua.org/
53//! [`Lua`]: crate::Lua
54//! [executing]: crate::Chunk::exec
55//! [evaluating]: crate::Chunk::eval
56//! [globals]: crate::Lua::globals
57//! [`IntoLua`]: crate::IntoLua
58//! [`FromLua`]: crate::FromLua
59//! [`IntoLuaMulti`]: crate::IntoLuaMulti
60//! [`FromLuaMulti`]: crate::FromLuaMulti
61//! [`Function`]: crate::Function
62//! [`UserData`]: crate::UserData
63//! [`UserDataFields`]: crate::UserDataFields
64//! [`UserDataMethods`]: crate::UserDataMethods
65//! [`LuaSerdeExt`]: crate::LuaSerdeExt
66//! [`Value`]: crate::Value
67//! [`create_async_function`]: crate::Lua::create_async_function
68//! [`call_async`]: crate::Function::call_async
69//! [`AsyncThread`]: crate::AsyncThread
70//! [`Future`]: std::future::Future
71//! [`serde::Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html
72//! [`serde::Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html
73
74// Deny warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show *any*
75// warnings at all.
76#![cfg_attr(docsrs, feature(doc_cfg))]
77
78#[macro_use]
79mod macros;
80
81mod chunk;
82mod conversion;
83mod error;
84mod function;
85mod hook;
86#[cfg(feature = "luau")]
87mod luau;
88mod memory;
89mod multi;
90// mod scope;
91mod state;
92mod stdlib;
93mod string;
94mod table;
95mod thread;
96mod traits;
97mod types;
98mod userdata;
99mod util;
100mod value;
101
102pub mod prelude;
103
104pub use bstr::BString;
105pub use ffi::{self, lua_CFunction, lua_State};
106
107pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
108pub use crate::error::{Error, ErrorContext, ExternalError, ExternalResult, Result};
109pub use crate::function::{Function, FunctionInfo};
110pub use crate::hook::{Debug, DebugEvent, DebugNames, DebugSource, DebugStack};
111pub use crate::multi::Variadic;
112pub use crate::state::{GCMode, Lua, LuaOptions};
113// pub use crate::scope::Scope;
114pub use crate::stdlib::StdLib;
115pub use crate::string::{BorrowedBytes, BorrowedStr, String};
116pub use crate::table::{Table, TablePairs, TableSequence};
117pub use crate::thread::{Thread, ThreadStatus};
118pub use crate::traits::ObjectLike;
119pub use crate::types::{AppDataRef, AppDataRefMut, Integer, LightUserData, MaybeSend, Number, RegistryKey};
120pub use crate::userdata::{
121    AnyUserData, MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods, UserDataRef,
122    UserDataRefMut, UserDataRegistry,
123};
124pub use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, MultiValue, Nil, Value};
125
126#[cfg(not(feature = "luau"))]
127pub use crate::hook::HookTriggers;
128
129#[cfg(any(feature = "luau", doc))]
130#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
131pub use crate::{
132    chunk::Compiler,
133    function::CoverageInfo,
134    types::{Vector, VmState},
135};
136
137#[cfg(feature = "async")]
138pub use crate::thread::AsyncThread;
139
140#[cfg(feature = "serialize")]
141#[doc(inline)]
142pub use crate::serde::{de::Options as DeserializeOptions, ser::Options as SerializeOptions, LuaSerdeExt};
143
144#[cfg(feature = "serialize")]
145#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
146pub mod serde;
147
148#[cfg(feature = "mlua_derive")]
149#[allow(unused_imports)]
150#[macro_use]
151extern crate mlua_derive;
152
153/// Create a type that implements [`AsChunk`] and can capture Rust variables.
154///
155/// This macro allows to write Lua code directly in Rust code.
156///
157/// Rust variables can be referenced from Lua using `$` prefix, as shown in the example below.
158/// User's Rust types needs to implement [`UserData`] or [`IntoLua`] traits.
159///
160/// Captured variables are **moved** into the chunk.
161///
162/// ```
163/// use mlua::{Lua, Result, chunk};
164///
165/// fn main() -> Result<()> {
166///     let lua = Lua::new();
167///     let name = "Rustacean";
168///     lua.load(chunk! {
169///         print("hello, " .. $name)
170///     }).exec()
171/// }
172/// ```
173///
174/// ## Syntax issues
175///
176/// Since the Rust tokenizer will tokenize Lua code, this imposes some restrictions.
177/// The main thing to remember is:
178///
179/// - Use double quoted strings (`""`) instead of single quoted strings (`''`).
180///
181///   (Single quoted strings only work if they contain a single character, since in Rust,
182///   `'a'` is a character literal).
183///
184/// - Using Lua comments `--` is not desirable in **stable** Rust and can have bad side effects.
185///
186///   This is because procedural macros have Line/Column information available only in
187///   **nightly** Rust. Instead, Lua chunks represented as a big single line of code in stable Rust.
188///
189///   As workaround, Rust comments `//` can be used.
190///
191/// Other minor limitations:
192///
193/// - Certain escape codes in string literals don't work. (Specifically: `\a`, `\b`, `\f`, `\v`,
194///   `\123` (octal escape codes), `\u`, and `\U`).
195///
196///   These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`.
197///
198/// - The `//` (floor division) operator is unusable, as its start a comment.
199///
200/// Everything else should work.
201///
202/// [`AsChunk`]: crate::AsChunk
203/// [`UserData`]: crate::UserData
204/// [`IntoLua`]: crate::IntoLua
205#[cfg(feature = "macros")]
206#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
207pub use mlua_derive::chunk;
208
209/// Derive [`FromLua`] for a Rust type.
210///
211/// Current implementation generate code that takes [`UserData`] value, borrow it (of the Rust type)
212/// and clone.
213#[cfg(feature = "macros")]
214#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
215pub use mlua_derive::FromLua;
216
217/// Registers Lua module entrypoint.
218///
219/// You can register multiple entrypoints as required.
220///
221/// ```
222/// use mlua::{Lua, Result, Table};
223///
224/// #[mlua::lua_module]
225/// fn my_module(lua: &Lua) -> Result<Table> {
226///     let exports = lua.create_table()?;
227///     exports.set("hello", "world")?;
228///     Ok(exports)
229/// }
230/// ```
231///
232/// Internally in the code above the compiler defines C function `luaopen_my_module`.
233///
234/// You can also pass options to the attribute:
235///
236/// * name - name of the module, defaults to the name of the function
237///
238/// ```ignore
239/// #[mlua::lua_module(name = "alt_module")]
240/// fn my_module(lua: &Lua) -> Result<Table> {
241///     ...
242/// }
243/// ```
244///
245/// * skip_memory_check - skip memory allocation checks for some operations.
246///
247/// In module mode, mlua runs in unknown environment and cannot say are there any memory
248/// limits or not. As result, some operations that require memory allocation runs in
249/// protected mode. Setting this attribute will improve performance of such operations
250/// with risk of having uncaught exceptions and memory leaks.
251///
252/// ```ignore
253/// #[mlua::lua_module(skip_memory_check)]
254/// fn my_module(lua: &Lua) -> Result<Table> {
255///     ...
256/// }
257/// ```
258#[cfg(any(feature = "module", docsrs))]
259#[cfg_attr(docsrs, doc(cfg(feature = "module")))]
260pub use mlua_derive::lua_module;
261
262pub(crate) mod private {
263    use super::*;
264
265    pub trait Sealed {}
266
267    impl Sealed for Error {}
268    impl<T> Sealed for std::result::Result<T, Error> {}
269    impl Sealed for Lua {}
270    impl Sealed for Table {}
271    impl Sealed for AnyUserData {}
272}