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