factorio_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 [`ToLua`] 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 [`ToLuaMulti`] 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 values
31//! and vice versa using serde. Any user defined data type that implements [`serde::Serialize`] or
32//! [`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 polling
44//! [`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 `Send` requirement
50//! 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//! [`ToLua`]: crate::ToLua
58//! [`FromLua`]: crate::FromLua
59//! [`ToLuaMulti`]: crate::ToLuaMulti
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// mlua types in rustdoc of other crates get linked to here.
75#![doc(html_root_url = "https://docs.rs/factorio-mlua/0.8.0")]
76// Deny warnings inside doc tests / examples. When this isn't present, rustdoc doesn't show *any*
77// warnings at all.
78#![doc(test(attr(deny(warnings))))]
79#![cfg_attr(docsrs, feature(doc_cfg))]
80
81#[macro_use]
82mod macros;
83
84mod chunk;
85mod conversion;
86mod error;
87mod ffi;
88mod function;
89mod hook;
90mod lua;
91#[cfg(feature = "luau")]
92mod luau;
93mod multi;
94mod scope;
95mod stdlib;
96mod string;
97mod table;
98mod thread;
99mod types;
100mod userdata;
101mod userdata_impl;
102mod util;
103mod value;
104
105pub mod prelude;
106
107pub use crate::{ffi::lua_CFunction, ffi::lua_State};
108
109pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
110pub use crate::error::{Error, ExternalError, ExternalResult, Result};
111pub use crate::function::{Function, FunctionInfo};
112pub use crate::hook::{Debug, DebugEvent, DebugNames, DebugSource, DebugStack};
113pub use crate::lua::{GCMode, Lua, LuaOptions};
114pub use crate::multi::Variadic;
115pub use crate::scope::Scope;
116pub use crate::stdlib::StdLib;
117pub use crate::string::String;
118pub use crate::table::{Table, TableExt, TablePairs, TableSequence};
119pub use crate::thread::{Thread, ThreadStatus};
120pub use crate::types::{Integer, LightUserData, Number, RegistryKey};
121pub use crate::userdata::{
122    AnyUserData, MetaMethod, UserData, UserDataFields, UserDataMetatable, UserDataMethods,
123};
124pub use crate::value::{FromLua, FromLuaMulti, MultiValue, Nil, ToLua, ToLuaMulti, 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::{chunk::Compiler, function::CoverageInfo, types::VmState};
132
133#[cfg(feature = "async")]
134pub use crate::thread::AsyncThread;
135
136#[cfg(feature = "serialize")]
137#[doc(inline)]
138pub use crate::serde::{
139    de::Options as DeserializeOptions, ser::Options as SerializeOptions, LuaSerdeExt,
140};
141
142#[cfg(feature = "serialize")]
143#[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
144pub mod serde;
145
146#[cfg(any(feature = "mlua_derive"))]
147#[allow(unused_imports)]
148#[macro_use]
149extern crate mlua_derive;
150
151#[cfg(feature = "lua-factorio")]
152extern crate link_cplusplus;
153
154/// Create a type that implements [`AsChunk`] and can capture Rust variables.
155///
156/// This macro allows to write Lua code directly in Rust code.
157///
158/// Rust variables can be referenced from Lua using `$` prefix, as shown in the example below.
159/// User's Rust types needs to implement [`UserData`] or [`ToLua`] traits.
160///
161/// Captured variables are **moved** into the chunk.
162///
163/// ```
164/// use mlua::{Lua, Result, chunk};
165///
166/// fn main() -> Result<()> {
167///     let lua = Lua::new();
168///     let name = "Rustacean";
169///     lua.load(chunk! {
170///         print("hello, " .. $name)
171///     }).exec()
172/// }
173/// ```
174///
175/// ## Syntax issues
176///
177/// Since the Rust tokenizer will tokenize Lua code, this imposes some restrictions.
178/// The main thing to remember is:
179///
180/// - Use double quoted strings (`""`) instead of single quoted strings (`''`).
181///
182///   (Single quoted strings only work if they contain a single character, since in Rust,
183///   `'a'` is a character literal).
184///
185/// - Using Lua comments `--` is not desirable in **stable** Rust and can have bad side effects.
186///
187///   This is because procedural macros have Line/Column information available only in
188///   **nightly** Rust. Instead, Lua chunks represented as a big single line of code in stable Rust.
189///
190///   As workaround, Rust comments `//` can be used.
191///
192/// Other minor limitations:
193///
194/// - Certain escape codes in string literals don't work.
195///   (Specifically: `\a`, `\b`, `\f`, `\v`, `\123` (octal escape codes), `\u`, and `\U`).
196///
197///   These are accepted: : `\\`, `\n`, `\t`, `\r`, `\xAB` (hex escape codes), and `\0`.
198///
199/// - The `//` (floor division) operator is unusable, as its start a comment.
200///
201/// Everything else should work.
202///
203/// [`AsChunk`]: crate::AsChunk
204/// [`UserData`]: crate::UserData
205/// [`ToLua`]: crate::ToLua
206#[cfg(any(feature = "macros"))]
207#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
208pub use mlua_derive::chunk;
209
210/// Registers Lua module entrypoint.
211///
212/// You can register multiple entrypoints as required.
213///
214/// ```
215/// use mlua::{Lua, Result, Table};
216///
217/// #[mlua::lua_module]
218/// fn my_module(lua: &Lua) -> Result<Table> {
219///     let exports = lua.create_table()?;
220///     exports.set("hello", "world")?;
221///     Ok(exports)
222/// }
223/// ```
224///
225/// Internally in the code above the compiler defines C function `luaopen_my_module`.
226///
227#[cfg(any(feature = "module", docsrs))]
228#[cfg_attr(docsrs, doc(cfg(feature = "module")))]
229pub use mlua_derive::lua_module;