Skip to main content

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 = "serde"`.
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//! [`AsyncThread`]: crate::thread::AsyncThread
65
66// Deny warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show *any*
67// warnings at all.
68#![cfg_attr(docsrs, feature(doc_cfg))]
69#![cfg_attr(not(send), allow(clippy::arc_with_non_send_sync))]
70#![allow(unsafe_op_in_unsafe_fn)]
71
72#[macro_use]
73mod macros;
74
75mod buffer;
76mod chunk;
77mod conversion;
78mod memory;
79mod multi;
80mod scope;
81mod stdlib;
82mod traits;
83mod types;
84mod util;
85mod value;
86mod vector;
87
88pub mod debug;
89pub mod error;
90pub mod function;
91#[cfg(any(feature = "luau", doc))]
92#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
93pub mod luau;
94pub mod prelude;
95pub mod state;
96pub mod string;
97pub mod table;
98pub mod thread;
99pub mod userdata;
100
101pub use bstr::BString;
102pub use ffi::{self, lua_CFunction, lua_State};
103
104pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
105#[doc(inline)]
106pub use crate::error::{Error, Result};
107#[doc(inline)]
108pub use crate::function::Function;
109pub use crate::multi::{MultiValue, Variadic};
110pub use crate::scope::Scope;
111#[doc(inline)]
112pub use crate::state::{Lua, LuaOptions, WeakLua};
113pub use crate::stdlib::StdLib;
114#[doc(inline)]
115pub use crate::string::{BorrowedBytes, BorrowedStr, LuaString};
116#[doc(inline)]
117pub use crate::table::Table;
118#[doc(inline)]
119pub use crate::thread::Thread;
120pub use crate::traits::{
121    FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, LuaNativeFn, LuaNativeFnMut, ObjectLike,
122};
123pub use crate::types::{
124    AppDataRef, AppDataRefMut, Either, Integer, LightUserData, MaybeSend, MaybeSync, Number, RegistryKey,
125    VmState,
126};
127#[doc(inline)]
128pub use crate::userdata::AnyUserData;
129pub use crate::value::{Nil, Value};
130
131// Re-export some types to keep backward compatibility and avoid breaking changes in the public API.
132#[doc(hidden)]
133pub use crate::error::{ErrorContext, ExternalError, ExternalResult};
134#[doc(hidden)]
135pub use crate::string::LuaString as String;
136#[doc(hidden)]
137pub use crate::table::{TablePairs, TableSequence};
138#[doc(hidden)]
139pub use crate::thread::ThreadStatus;
140#[doc(hidden)]
141pub use crate::userdata::{
142    MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods, UserDataRef, UserDataRefMut,
143    UserDataRegistry,
144};
145
146#[cfg(not(feature = "luau"))]
147#[doc(inline)]
148pub use crate::debug::HookTriggers;
149
150#[cfg(any(feature = "luau", doc))]
151#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
152pub use crate::{
153    buffer::Buffer,
154    chunk::{CompileConstant, Compiler},
155    vector::Vector,
156};
157
158#[cfg(feature = "async")]
159#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
160pub use crate::traits::LuaNativeAsyncFn;
161
162#[cfg(feature = "serde")]
163#[doc(inline)]
164pub use crate::{
165    serde::{LuaSerdeExt, de::Options as DeserializeOptions, ser::Options as SerializeOptions},
166    value::SerializableValue,
167};
168
169#[cfg(feature = "serde")]
170#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
171pub mod serde;
172
173#[cfg(feature = "mlua_derive")]
174#[allow(unused_imports)]
175#[macro_use]
176extern crate mlua_derive;
177
178/// Create a type that implements [`AsChunk`] and can capture Rust variables.
179///
180/// This macro allows to write Lua code directly in Rust code.
181///
182/// Rust variables can be referenced from Lua using `$` prefix, as shown in the example below.
183/// User's Rust types needs to implement [`UserData`] or [`IntoLua`] traits.
184///
185/// Captured variables are **moved** into the chunk.
186///
187/// ```
188/// use mlua::{Lua, Result, chunk};
189///
190/// fn main() -> Result<()> {
191///     let lua = Lua::new();
192///     let name = "Rustacean";
193///     lua.load(chunk! {
194///         print("hello, " .. $name)
195///     }).exec()
196/// }
197/// ```
198///
199/// ## Syntax issues
200///
201/// Since the Rust tokenizer will tokenize Lua code, this imposes some restrictions.
202/// The main thing to remember is:
203///
204/// - Use double quoted strings (`""`) instead of single quoted strings (`''`).
205///
206///   (Single quoted strings only work if they contain a single character, since in Rust,
207///   `'a'` is a character literal).
208///
209/// - Using Lua comments `--` is not desirable in **stable** Rust and can have bad side effects.
210///
211///   This is because procedural macros have Line/Column information available only in
212///   **nightly** Rust. Instead, Lua chunks represented as a big single line of code in stable Rust.
213///
214///   As workaround, Rust comments `//` can be used.
215///
216/// Other minor limitations:
217///
218/// - Certain escape codes in string literals don't work. (Specifically: `\a`, `\b`, `\f`, `\v`,
219///   `\123` (octal escape codes), `\u`, and `\U`).
220///
221///   These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`.
222///
223/// - The `//` (floor division) operator is unusable, as its start a comment.
224///
225/// Everything else should work.
226#[cfg(feature = "macros")]
227#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
228pub use mlua_derive::chunk;
229
230/// Derive [`FromLua`] for a Rust type.
231///
232/// Current implementation generate code that takes [`UserData`] value, borrow it (of the Rust type)
233/// and clone.
234#[cfg(feature = "macros")]
235#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
236pub use mlua_derive::FromLua;
237
238/// Registers Lua module entrypoint.
239///
240/// You can register multiple entrypoints as required.
241///
242/// ```ignore
243/// use mlua::{Lua, Result, Table};
244///
245/// #[mlua::lua_module]
246/// fn my_module(lua: &Lua) -> Result<Table> {
247///     let exports = lua.create_table()?;
248///     exports.set("hello", "world")?;
249///     Ok(exports)
250/// }
251/// ```
252///
253/// Internally in the code above the compiler defines C function `luaopen_my_module`.
254///
255/// You can also pass options to the attribute:
256///
257/// * name - name of the module, defaults to the name of the function
258///
259/// ```ignore
260/// #[mlua::lua_module(name = "alt_module")]
261/// fn my_module(lua: &Lua) -> Result<Table> {
262///     ...
263/// }
264/// ```
265///
266/// * skip_memory_check - skip memory allocation checks for some operations.
267///
268/// In module mode, mlua runs in an unknown environment and cannot tell whether there are any memory
269/// limits or not. As a result, some operations that require memory allocation run in protected
270/// mode. Setting this attribute will improve performance of such operations with risk of having
271/// uncaught exceptions and memory leaks.
272///
273/// ```ignore
274/// #[mlua::lua_module(skip_memory_check)]
275/// fn my_module(lua: &Lua) -> Result<Table> {
276///     ...
277/// }
278/// ```
279#[cfg(all(feature = "mlua_derive", any(feature = "module", doc)))]
280#[cfg_attr(docsrs, doc(cfg(feature = "module")))]
281pub use mlua_derive::lua_module;
282
283#[cfg(all(feature = "module", feature = "send"))]
284compile_error!("`send` feature is not supported in module mode");
285
286pub(crate) mod private {
287    use super::*;
288
289    pub trait Sealed {}
290
291    impl Sealed for Error {}
292    impl<T> Sealed for std::result::Result<T, Error> {}
293    impl Sealed for Lua {}
294    impl Sealed for Table {}
295    impl Sealed for AnyUserData {}
296}