NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
crates.io
crates.io, #3866 most downloaded on crates.io
High level bindings to Lua 5.5/5.4/5.3/5.2/5.1 (including LuaJIT) and Luau with async/await features and support of writing native Lua modules in Rust.
Latest stable
0.12.2
Last release 1 months ago
03 Oct 2026
Ships fairly regularly
a new release about every 5 weeks
Nearly every release is documented
notes for 55 of the last 60 stable releases
1 version withdrawn
withdrawn after publishing
7 years old
87 releases · first in 2019
Drag across the ruler to compare, or tap a release to open it.
Added recursion_limit to SerializeOptions and DeserializeOptions (defaults to 128)
Value::weak_lua helper (#714)recursion_limit to SerializeOptions and DeserializeOptions (defaults to 128)ValuesTable::equals now follows the backend's native __eq semanticsrequire from chunks loaded by path (#735) and require context lifetimesFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.12.1...v0.12.2
Allow #[mlua::userdata_impl] to be used in a different module from #[derive(UserData)]
#[mlua::userdata_impl] to be used in a different module from #[derive(UserData)] (#726)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.12.0...v0.12.1
Your coding agent can read these notes before it upgrades. Set up the MCP server →
Declaratively implement UserData with #[derive(UserData)] and register methods/fields with the new #[mlua::userdata_impl] attribute macro.
UserData with #[derive(UserData)] and register methods/fields with the new #[mlua::userdata_impl] attribute macro.UserDataOwned<T> wrapper takes ownership of userdata and implements FromLuaUserDataMethods::add_method_once/add_async_method_once__todebugstring metamethod for pretty-printing userdata when debuggingMaybeSync trait for userdata under the send featureTypes are now grouped into focused modules: chunk, debug, error, function, table, string, state, thread, userdata and luau.
Hook into coroutine create/resume/yield events across all Lua versions (when using mlua API).
Latest Luau with extended require-by-string support and JIT options.
Lua::gc_inc / Lua::gc_gen are replaced by a Lua::gc_set_mode, with GcIncParams/GcGenParams for fine-grained tuning.
ThreadStatus::Normal and Thread::is_normal (mimic coroutine.status)Lua::set_jit_options with support of Luau JIT inliner (Luau)Value::as_vector/Value::is_vector (Luau)Table::removeserde: tables with the array metatable are always encoded as arrays (incl. detect_mixed_tables option)Hash for BorrowedStr/BorrowedBytesLua::current_thread resolves implicit async threads to their root owner (#706)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.6...v0.12.0
The new stable version is almost ready and will be released after some testing
The new stable version is almost ready and will be released after some testing
#[derive(UserData)] and #[userdata_impl] macrosto_alias_override/to_alias_fallback in Require trait (Luau)String::to_pointer return NULL in Lua <5.4Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.12.0-rc.1...v0.12.0-rc.2
Removed Error::ToLuaConversionError variant as it was unused (and not practically useful)
Error::ToLuaConversionError variant as it was unused (and not practically useful)chunk, debug, error, function, table, string, state, thread, userdata, luau__todebugstring metamethod for pretty formatting userdata value (for debugging)MaybeSync trait that is required for userdata typesBorrowedStr and BorrowedBytesThread methods: is_resumable, is_running, is_finished, is_errorThread::state to get raw Lua state pointerTextRequirer is renamed to FsRequirerLua::gc_inc/Lua::gc_gen is replaced with gc_set_modeGcIncParams and GcGenParams for GC tuningUserDataMethods::add_method_once and UserDataMethods::add_async_method_onceFunction::wrap/wrap_mut/wrap_async to support any Error typeAnyUserData::type_name to return LuaString insteadUserDataOwned<T> wrapper to take ownership of userdata T and implements FromLuaFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.6...v0.12.0-rc.1
Lua 5.5 support under the new lua55 feature flag
lua55 feature flagAnyUserData::is_proxynum_params, num_upvalues, is_vararg to FunctionInfoFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.5...v0.11.6
Lua 5.5 support external strings and mlua enable this optimisation for impl IntoLua for String/BString (owned versions to move Drop into Lua).
Also the Lua::create_external_string function allow moving ownership to Lua for any Into<Vec<u8>> types.
lua55 feature flag)AnyUserData::is_proxy method to check if userdata is a proxynum_params, num_upvalues, is_vararg to FunctionInfoAdded Lua::set_memory_category and Lua::heap_dump functions to profile (Luau) memory
Lua::set_memory_category and Lua::heap_dump functions to profile (Luau) memoryLua::type_metatable helper to get metatable of a primitive typeLua::traceback function to generate stack traces at different levelsadd_method_once /add_async_method_once UserData methods (experimental)AnyUserData::type_name publicIntoLuaMulti for &MultiValueFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.4...v0.11.5
Make Value::to_serializable public
Value::to_serializable publicserde option detect_mixed_tables (to encode mixed array+map tables)ObjectLike::get_path helper (for tables and userdata) for easy access of nested data__namecall optimization for LuauFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.3...v0.11.4
Value::to_serializable publicdetect_mixed_tables (to encode mixed array+map tables)ObjectLike::get_path helper (for tables and userdata)Added Lua::yield_with to use as coroutine.yield functional replacement in async functions for any Lua (see doc examples)
Lua::yield_with to use as coroutine.yield functional replacement in async functions for any Lua (see doc examples)Buffer::cursor method (Luau)Lua::create_buffer_with_capacity method (Luau)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.2...v0.11.3
Lua::yield_with to use as coroutine.yield functional replacement in async functions for any LuaBuffer::cursor method (Luau)Lua::create_buffer_with_capacity method (Luau)Fix handling Windows paths with drive letter in Luau require (#623) by @piz-ewing
Variadic<T>-0.0 (#618)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.1...v0.11.2
Fixed bug exhausting Lua auxiliary stack and leaving it without reserve
Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.0...v0.11.1
Debug::curr_line is deprecated in favour of Debug::current_line that returns Option
external mlua-sys feature flagLua::inspect_stack takes a callback with &Debug argument, instead of returning Debug directlyDebug::function method to get function running at a given levelDebug::curr_line is deprecated in favour of Debug::current_line that returns Option<usize>Lua::set_globals method to replace global environmentTable::set_metatable now returns Result<()> (this operation can fail in sandboxed Luau mode)impl ToString replaced with Into<StdString> in UserData registrationValue::as_str and Value::as_string_lossy methods are deprecated (as they are non-idiomatic)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.0-beta.3...v0.11.0
Luau in sandboxed mode has reduced options in collectgarbage function (to follow the official doc)
collectgarbage function (to follow the official doc)Function::deep_clone now returns Result<Function> as this operation can fail with OOMAsyncThread on drop (call_async methods family)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.0-beta.2...v0.11.0-beta.3
collectgarbage function (to follow the official doc)Function::deep_clone now returns Result<Function> as this operation can trigger memory errorsAsyncThread on drop (call_async methods family)Terminate Rust Future when AsyncThread is dropped (without relying on Lua GC)
Future when AsyncThread is dropped (without relying on Lua GC)loadstring function to LuauAsChunk trait dyn-friendlyRequire trait synced with Luau 0.674Require trait methods now can return Error variant (in NavigateError enum)__type to Error's userdata metatable (for typeof function)parking_log/send_guard is moved to userdata-wrappers feature flagserde feature flag to replace serialize (the old one is still available)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.11.0-beta.1...v0.11.0-beta.2
52 bit integers support for Luau (this is a breaking change)
Require trait and async support)Thread::resume_error support for LuauAsyncThread<A, R> changed to AsyncThread<R> (A pushed to stack immediately)'a moved from AsChunk<'a> to AsChunk::sourceLua::scope pass &Scope instead of &mut Scope to closureLua::init_from_ptr renamed to Lua::get_or_init_from_ptr and returns &LuaLua:load_from_function is deprecated (this is register_module now)Lua::register_module and Lua::preload_moduleFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.10.4...v0.11.0-beta.1
Reverted: Added large (52bit) integers support for Luau (breaking change)
Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.10.4...v0.10.5
_yanked_ because of breaking semver (large integers for Luau changed type from i32 to i64)
yanked because of breaking semver (large integers for Luau changed type from i32 to i64)
encode_empty_tables_as_array to serialize empty tables as arrayWeakLua and Lua::weak() to create weak references to Lua stateAnyUserData::type_id() method to get the type id of the userdataChunk::name(), Chunk::environment() and Chunk::mode() functionsUserDataRef and UserDataRefMut (under userdata-wrappers feature)serde for bstr if serialize feature flag is enabledIntoLua/FromLua for BorrowedString and BorrowedBytesIntoLua/FromLua for charThread::reset() for all Lua versions (limited support for 5.1-5.3)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.10.3...v0.10.4
Set Default for Value to be Nil
Default for Value to be NilValue (#502)Table::set_safeenv method (Luau)Switch proc-macro-error to proc-macro-error2 by @evie-calico in https://github.com/mlua-rs/mlua/pull/493
String::wrap method to wrap arbitrary AsRef<[u8]> into impl IntoLuaUserData (less generics)Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.10.1...v0.10.2
Added Luau native vector library support (this can change behavior if you use vector function!)
vector function!)String::display methodScope::create_any_userdata to create Lua objects from any non-'static Rust typesAnyUserData::destroy methoduserdata-wrappers feature to impl UserData for Rc<T>/Arc<T>/Rc<RefCell<T>>/Arc<Mutex<T>> (similar to v0.9)UserDataRef in send mode now uses shared lock if T: Sync (and exclusive lock otherwise)Scope::add_destructor to attach custom destructorsLua::try_app_data_ref and Lua::try_app_data_mut methodsFrom<Vec> and Into<Vec> support to MultiValue and Variadic typesFor full changelog see changes in [v0.10.0-beta.1], [v0.10.0-beta.2] and [v0.10.0-rc.1] versions.
For full changelog see changes in v0.10.0-beta.1, v0.10.0-beta.2 and v0.10.0-rc.1 versions.
Most notable changes since v0.9:
'lua lifetimeSend + Sync with send feature flagLua::exec_raw helper to execute low-level Lua C API codeLuaNativeFn/LuaNativeFnMut/LuaNativeAsyncFn traits for using in Function::wrapChanges since v0.10.0-rc.1
error-send feature flag (disabled by default) to require Send + Sync for ErrorThe v0.10 version of mlua has a goal to improve the user experience while keeping the same performance and safety guarantees. This document highlights the most notable features. For a full list of changes, see the CHANGELOG.
'static Lua typesIn previous mlua versions, it was required to have a 'lua lifetime attached to every Lua value. v0.9 introduced (experimental) owned types that are 'static without a lifetime attached, but they kept strong references to the Lua instance.
In v0.10 all Lua types are 'static and have only weak reference to the Lua instance. It means they are more flexible and can be used in more places without worrying about memory leaks.
send featureIn this version Lua is Send + Sync when the send feature flag is enabled (previously was only Send). It means Lua instance and their values can be safely shared between threads and used in multi threaded async contexts.
let lua = Lua::new();
lua.globals().set("i", 0)?;
let func = lua.load("i = i + ...").into_function()?;
std::thread::scope(|s| {
s.spawn(|| {
for i in 0..5 {
func.call::<()>(i).unwrap();
}
});
s.spawn(|| {
for i in 0..5 {
func.call::<()>(i).unwrap();
}
});
});
assert_eq!(lua.globals().get::<i32>("i")?, 20);
Under the hood, to synchronize access to the Lua state, mlua uses ReentrantMutex which can be recursively locked by a single thread. Only one thread can execute Lua code at a time, but it's possible to share Lua values between threads.
This has some performance penalties (about 10-20%) compared to the lock free mode. This flag is disabled by default and is not supported in module mode.
The new traits LuaNativeFn/LuaNativeFnMut/LuaNativeAsyncFn have been introduced to provide a way to register Rust functions with variable number of arguments in Lua, without needing to pass all arguments as a tuple.
They are used by Function::wrap/Function::wrap_mut/Function::wrap_async methods:
let add = Function::wrap(|a: i64, b: i64| Ok(a + b));
lua.globals().set("add", add).unwrap();
// Prints 50
lua.load(r#"print(add(5, 45))"#).exec().unwrap();
To wrap functions that return direct value (non-Result) you can use Function::wrap_raw method.
For Lua builtin types (like string, function, number, etc.) that have a shared metatable for all instances, it's now possible to set a custom metatable for them.
let mt = lua.create_table()?;
mt.set("__tostring", lua.create_function(|_, b: bool| Ok(if b { "2" } else { "0" }))?)?;
lua.set_type_metatable::<bool>(Some(mt));
lua.load("assert(tostring(true) == '2')").exec().unwrap();
ObjectLike traitThe ObjectLike trait is a combination of the AnyUserDataExt and TableExt traits used in previous versions. It provides a unified interface for working with Lua tables and userdata.
Either<L, R> enumThe Either<L, R> enum is a simple enum that can hold either L or R value. It's useful when you need to return or receive one of two types in a function.
This type implements IntoLua and FromLua traits and can generate a meaningful error message when conversion fails.
let func = Function::wrap(|x: Either<i32, String>| Ok(format!("received: {x}")));
lua.globals().set("func", func).unwrap();
// Prints: received: 123
lua.load(r#"print(func(123))"#).exec().unwrap();
// Prints: bad argument #1: error converting Lua table to Either<i32, String>
lua.load(r#"print(pcall(func, {}))"#).exec().unwrap();
Lua::exec_raw helper to execute low-level Lua C API codeFor advanced users, it's now possible to execute low-level Lua C API code using the Lua::exec_raw method.
let t = lua.create_sequence_from([1, 2, 3, 4, 5])?;
let sum: i64 = unsafe {
lua.exec_raw(&t, |state| {
// top of the stack: table `t`
let mut sum = 0;
// push nil as the first key
mlua::ffi::lua_pushnil(state);
while mlua::ffi::lua_next(state, -2) != 0 {
sum += mlua::ffi::lua_tointeger(state, -1);
// Remove the value, keep the key for the next iteration
mlua::ffi::lua_pop(state, 1);
}
mlua::ffi::lua_pop(state, 1);
mlua::ffi::lua_pushinteger(state, sum);
// top of the stack: sum
})
}?;
assert_eq!(sum, 15);
The exec_raw method is longjmp-safe. It's not recommended to move Drop types into the closure to avoid possible memory leaks.
anyhow feature flagThe new anyhow feature flag adds IntoLua and Into<mlua::Error> implementation for the anyhow::Error type.
let f = lua.create_function(|_, ()| {
Err(anyhow!("error message"))?;
Ok(())
})?;
The following Scope methods were changed:
Scope::create_any_userdataScope::create_nonstatic_userdata is renamed to Scope::create_userdataInstead, scope has comprehensive support for borrowed userdata: create_any_userdata_ref, create_any_userdata_ref_mut, create_userdata_ref, create_userdata_ref_mut.
UserDataRef and UserDataRefMut are no longer acceptable for scoped userdata access as they require owned underlying data.
In mlua v0.9 this could cause a read-after-free bug in some edge cases.
To temporarily borrow underlying data, the AnyUserData::borrow_scoped and AnyUserData::borrow_mut_scoped methods were introduced:
let data = "hello".to_string();
lua.scope(|scope| {
let ud = scope.create_any_userdata_ref(&data)?;
// We can only borrow scoped userdata using this method
ud.borrow_scoped::<String, ()>(|s| {
assert_eq!(s, "hello");
})?;
Ok(())
})?;
Those methods work for scoped and regular userdata objects (but still require T: 'static).
Since mlua::String holds a weak reference to Lua without any guarantees about the lifetime of the underlying data, getting a &str or &[u8] from it is no longer safe.
Lua instance can be destroyed while reference to the data is still alive:
let lua = Lua::new();
let s: mlua::String = lua.create_string("hello, world")?; // only weak reference to Lua!
let s_ref: &str = s.to_str()?; // this is not safe!
drop(lua);
println!("{s_ref}"); // use after free!
To solve this issue, return types of mlua::String::to_str and mlua::String::as_bytes methods changed to BorrowedStr and BorrowedBytes respectively.
These new types hold a strong reference to the Lua instance and can be safely converted to &str or &[u8]:
let lua = Lua::new();
let s: mlua::String = lua.create_string("hello, world")?;
let s_ref: mlua::BorrowedStr = s.to_str()?; // The strong reference to Lua is held here
drop(lua);
println!("{s_ref}"); // ok
The good news is that BorrowedStr implements Deref<Target = str>/AsRef<str> as well as Display, Debug, Eq, PartialEq and other traits for easy usage.
The same applies to BorrowedBytes.
Unfortunately, mlua::String::to_string_lossy cannot return Cow<'a, str> anymore, because it requires a strong reference to Lua. It now returns Rust String instead.
Support yielding from hooks for Lua 5.3+
Lua::scope is backLuaNativeFn/LuaNativeFnMut/LuaNativeAsyncFn traits for using in Function::wrapError::chain method to return iterator over nested errorsLua::exec_raw helper to execute low-level Lua C API codeEither<L, R> enum to combine two types into a single oneBuffer type for LuauValue::is_error and Value::as_error helpersValue::Other variant to represent unknown Lua types (eg LuaJIT CDATA)anyhow feature to implement IntoLua for anyhow::Errormlua is getting close to v0.10 stable release. Send+Sync works well and hopefully all unsoundness are fixed.
mlua is getting close to v0.10 stable release. Send+Sync works well and hopefully all unsoundness are fixed.
Few (planned) features left:
Either<A, B> enum that implements FromLuaLuaNativeFn trait to wrap Rust functions with non-tuple args (will be used in Function::wrap*)IntoLua derive macroThreadStatus enum to include Running and Finished variants.Error::CoroutineInactive renamed to Error::CoroutineUnresumable.IntoLua/IntoLuaMulti now uses impl trait syntax for args (shorten from a.get::<_, T> to a.get::<T>).Lua::into_static/from_static methods.Send bound if send feature is enabled.UserDataMethods and UserDataFields traits.Compiler::compile() now returns Result (Luau).Clone requirement from UserDataFields::add_field().TableExt and AnyUserDataExt traits were combined into ObjectLike trait.send feature in module mode (since we don't have exclusive access to Lua).Chunk::set_environment() takes Table instead of IntoLua type.next_key_seed and next_value_seed.serde_userdata.Full Changelog: https://github.com/mlua-rs/mlua/compare/v0.10.0-beta.1...v0.10.0-beta.2
Dropped 'lua lifetime (subtypes now store a weak reference to Lua)
'lua lifetime (subtypes now store a weak reference to Lua)Send and Sync (when enabling send feature flag)UserData impl for Rc/Arc types ("any" userdata functions can be used instead)Lua::replace_registry_value takes &mut RegistryKeyLua::scope temporary disabled (will be re-added in the next release)Fixed bug when attempting to reset or resume already running coroutines (#416).
RegistryKey::id() method to get the underlying Lua registry key id.Fixed serializing same table multiple times
mlua-sys v0.6 (to support Luau 0.624+)Implemented IntoLua for RegistryKey
IntoLua for RegistryKey__idiv metamethod as available for LuauFunction::deep_clone() method (Luau)SerializeOptions::detect_serde_json_arbitrary_precision optionLua::create_buffer() method (Luau)push_into_stack/from_stack for Option<T>Lua::create_ser_any_userdata() methodFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.9.6...v0.9.7
Added to_pointer function to Function/Table/Thread
to_pointer function to Function/Table/ThreadIntoLua for &ValueFromLua for RegistryKeyFull Changelog: https://github.com/mlua-rs/mlua/compare/v0.9.5...v0.9.6
Luau max stack size increased to 1M (from 100K)
IntoLua for refs to String/Table/Function/AnyUserData/Thread + RegistryKeyIntoLua and FromLua for OwnedThread/OwnedString (unstable feature)FromLua derive proc macro to cover more casesFixed loading all-in-one modules under mixed states (eg. main state and coroutines)
WebAssembly support (wasm32-unknown-emscripten target)
wasm32-unknown-emscripten target)Added binary modules support to Luau
StdLib::PACKAGE) with loaders (follows lua5.1 interface)cdata type is also represented as userdata in Rust (instead of panic)Table::for_each method for fast table pairs traversal (faster than pairs)impl IntoLuaMulti for std::Result<(), E>
std::result::Result<(), E>Improved non-static (scoped) userdata support
Changes since v0.9.0-rc.3
Scope::create_any_userdata() methodLua::set_vector_metatable() method (unstable feature flag)OwnedThread type (unstable feature flag)sort_keys to DeserializeOptions (Lua::from_value() method)Table::raw_len() output type to usizeValue (eg: Value::as_number()/Value::as_string/etc)The v0.9 version of mlua is a major release that includes a number of API changes and improvements. This release is a stepping stone towards the v1.0. This document highlights the most important changes. For a full list of changes, see the CHANGELOG.
This is a long awaited feature that allows to register in Lua foreign types that cannot implement UserData trait because of the Rust orphan rules.
Now you can register any type that implements Any trait as a userdata type.
Consider the following example:
lua.register_userdata_type::<std::string::String>(|reg| {
reg.add_method("len", |_, this, ()| Ok(this.len()));
reg.add_method_mut("push", |_, this, s: String| {
this.push_str(&s);
Ok(())
});
reg.add_meta_method(MetaMethod::ToString, |lua, this, ()| lua.create_string(this));
})?;
let s = lua.create_any_userdata("hello".to_string())?;
lua.load(chunk! {
print("s:len() is " .. $s:len())
$s:push(" world")
// Prints: hello, world
print($s)
})
.exec()?;
In this example we registered std::string::String as a userdata type with a set of methods and then created an instance of this type in Lua.
It's not required to register a type before using the Lua::create_any_userdata() method, instead an empty metatable will be created for you.
You can also register the same type multiple times with different methods. Any previously created instances will share the old metatable, while new instances will have the new one.
The new set of API is called any_userdata because it allows to register types that implements Any trait.
When you need to create non-static userdata instances in Lua, the usual way is use Lua::scope() helper to make them scoped. When out of scope, any scoped objects will be automatically
dropped. The only downside of this approach is that every new instance will have a new metatable. This is not very fast if you need to create a lot of instances.
With the new Any UserData API, you can place non-static references &T where T: 'static into a scope and they will share a single static metatable.
lua.register_userdata_type::<std::string::String>(|reg| {
reg.add_method_mut("replace", |_, this, (pat, to): (String, String)| {
*this = this.replace(&pat, &to);
Ok(())
});
reg.add_meta_method(MetaMethod::ToString, |lua, this, ()| lua.create_string(this));
})?;
let mut s = "hello, world".to_string();
lua.scope(|scope| {
// This userdata instance holds only a mutable reference to our string
let ud = scope.create_any_userdata_ref_mut(&mut s)?;
lua.load(chunk! {
$ud:replace("world", "user")
})
.exec()
})?;
// Prints: hello, user!
println!("{s}!");
unstable)One of the common questions was how to embed a Lua type into Rust struct to use it later. It was non-trivial to do because of the 'lua lifetime attached to every Lua value.
In v0.9 mlua introduces "owned" types OwnedTable/OwnedFunction/OwnedString/OwnedAnyUserData/ OwnedThreadthat are 'static (no lifetime attached).
let lua = Lua::new();
struct MyStruct {
table: OwnedTable,
func: OwnedFunction,
}
let my_struct = MyStruct {
table: lua.globals().into_owned(),
func: lua
.create_function(|_, t: Table| Ok(format!("{t:#?}")))?
.into_owned(),
};
// It's safe to drop Lua!
drop(lua);
let result = my_struct.func.call::<_, String>(my_struct.table)?;
println!("{result}");
Prior to v0.9, it was possible to do by creating a reference to the Lua value in registry using Lua::create_registry_value()
and retrieving value later using Lua::registry_value() method.
All owned handles hold a strong reference to the current Lua instance.
Be warned, if you place them into a Lua type (eg. UserData or a Rust callback), it is very easy
to accidentally cause reference cycles that would prevent destroying Lua instance.
Please note this functionality is available under the unstable feature flag and not available when the send feature is enabled.
In v0.9 release the internal ffi module has been moved into the new mlua-sys crate and became available for public use.
This crate provides unified Lua FFI API (targeting Lua 5.4) using a (limited) compatibility layer for older versions.
mlua re-exports the ffi module aliasing the mlua-sys crate and provides (unsafe) functionality to work with raw Lua state:
unsafe {
unsafe extern "C-unwind" fn lua_add(state: *mut mlua::lua_State) -> i32 {
let a = mlua::ffi::luaL_checkinteger(state, 1);
let b = mlua::ffi::luaL_checkinteger(state, 2);
mlua::ffi::lua_pushinteger(state, a + b);
1
}
let add = lua.create_c_function(lua_add)?;
assert_eq!(add.call::<_, i32>((2, 3))?, 5);
}
mlua brings support for the new Luau JIT backend under the luau-jit feature flag.
It will automatically trigger JIT compilation for new Lua chunks. To disable it, just call lua.enable_jit(false) before loading Lua code
(but any previously compiled chunks will remain JIT-compiled).
When calling a Rust function from Lua and passing wrong arguments, previous mlua versions reported an error message without any context or reference to the particular argument.
In v0.9 it reports an error message with the argument index and expected type:
let func = lua.create_function(|_, _a: i32| Ok(()))?;
lua.load(chunk! {
local ok, err = pcall($func, "not a number")
// Prints: bad argument #1: error converting Lua string to i32 (expected number or string coercible to number)
print(err)
})
.exec()?;
Similar changes have been made for userdata functions and methods:
lua.register_userdata_type::<&'static str>(|reg| {
reg.add_method("len", |_, this, ()| Ok(this.len()));
})?;
let s = lua.create_any_userdata("hello")?;
lua.load(chunk! {
local ok, err = pcall($s.len, 123)
// Prints: bad argument `self` to `&str.len`: error converting Lua integer to userdata
print(err)
})
.exec()?;
Similar to the anyhow Error type, now it's possible to attach context to Lua errors:
let read = lua.create_function(|lua, path: String| {
let bytes = std::fs::read(&path)
.into_lua_err()
.context(format!("Failed to open `{path}`"))?;
Ok(lua.create_string(bytes))
})?;
lua.load(chunk! {
local ok, err = pcall($read, "/nonexistent")
/// Prints:
/// Failed to open /nonexistent
/// No such file or directory (os error 2)
/// stack traceback:
/// ...
print(err)
})
.exec()?;
Function::wrap/AnyUserData::wrapSometimes it's useful to have IntoLua trait implementation for a Rust function or type T: Any without needing to call Lua::create_function()/Lua::create_any_userdata() methods.
Since v0.9 you can call the new methods Function::wrap()/AnyUserData::wrap() that allows to do this. They return an abstract type that impl IntoLua:
lua.globals().set("print_rust", Function::wrap(|_, s: String| Ok(println!("{}", s))))?;
lua.globals().set("rust_ud", AnyUserData::wrap("hello"))?;
In addition there are also Function::wrap_mut()/Function::wrap_async() methods that allow to wrap mutable and async functions respectively.
For a T: 'UserData + 'static the IntoLua trait is still always implemented.
UserDataRef and UserDataRefMut type wrappersThe new wrappers UserDataRef and UserDataRefMut are receivers for userdata type T and borrow underlying instance for the lifetime of the wrapper.
lua.globals()
.set("ud", AnyUserData::wrap("hello".to_string()))?;
let mut ud_mut: UserDataRefMut<String> = lua.globals().get("ud")?;
ud_mut.push_str(", Rust");
drop(ud_mut);
let ud_ref: UserDataRef<String> = lua.globals().get("ud")?;
// Prints: hello, Rust
println!("{}", *ud_ref);
In the previous mlua versions the same functionality can be achieved by receiving AnyUserData and calling AnyUserData::borrow()/AnyUserData::borrow_mut() methods.
The new wrappers are identical to Rust Ref/RefMut types.
AnyUserDataExt traitSimilar to the TableExt trait, the AnyUserDataExt provides a set of extra methods for the AnyUserData type.
AnyUserDataExt::get()/set() to get/set a value by key from the userdata, assuming it has __index metamethod.
AnyUserDataExt::call() to call the userdata as a function assuming it has __call metamethod.
AnyUserData::call_method(name, ...) to call the userdata method, assuming it has __index metamethod and the associated function.
mlua::Value implements a new format :#? that allows to (recursively) pretty print Lua values:
println!("{:#?}", lua.globals());
Prints:
{
["_G"] = table: 0x7fa2d0706260,
["_VERSION"] = "Lua 5.4",
["assert"] = function: 0x10451d11d,
["collectgarbage"] = function: 0x10451d198,
["coroutine"] = {
["close"] = function: 0x10451e28f,
...
},
["dofile"] = function: 0x10451d37c,
...
}
In addition a new method Value::to_string() has been added to convert Value to a string (using __tostring metamethod if available).
Any Lua functions have an associated environment table that is used to resolve global variables. By default it sets to a Lua globals table.
In the new release it's possible to get or update a function environment using Function::environment() or Function::set_environment() methods respectively.
let f = lua.load("return a").into_function()?;
assert_eq!(f.environment(), Some(lua.globals()));
lua.globals().set("a", 1)?;
assert_eq!(f.call::<_, i32>(())?, 1);
f.set_environment(lua.create_table_from([("a", "hello")])?)?;
assert_eq!(f.call::<_, mlua::String>(())?, "hello");
The new mlua version has a number of performance improvements. Please check the benchmarks results to see how mlua compares to rlua and rhai.
module modeThe lua_module macro now support the following attributes:
name=... - sets name of the module (defaults to the name of the function).Eg.:
#[mlua::lua_module(name = "alt_module")]
fn my_module(lua: &Lua) -> LuaResult<LuaTable> {
lua.create_table()
}
Under the hood a new function luaopen_alt_module will be created for the Lua module loader.
skip_memory_check - skip memory allocation checks for some operations.In module mode, mlua runs in an unknown environment and cannot tell whether there are any memory limits or not. As a result, some operations that require memory allocation run in protected mode. Setting this attribute will improve performance of such operations with risk of having uncaught exceptions and memory leaks.
In previous mlua versions, building a Lua module for Windows requires having Lua development libraries installed on the system.
In contrast, on Linux and macOS, modules can be built without any external dependencies using the -undefined=dynamic_lookup linker flag.
With Rust 1.71+ it's now possible to lift this restriction for Windows as well. You can build modules normally and they will be linked with
lua5x.dll depending on the enabled Lua version.
You still need to have the dll although, linked to application where the module will be loaded.
ToLua/ToLuaMulti traits have been renamed to IntoLua/IntoLuaMulti respectively (with the methods called into_lua/into_lua_multi).The main reason for this change is following the Rust self convention.
FromLua implementation for T: UserData + Clone.During the usage of mlua, it was found that this implementation is not very useful and prevents custom FromLua implementations for T: UserData.
It should be a developer decision to opt-in FromLua for their T if needed rather than having enabled it unconditionally.
To opt-in FromLua for T: Clone you can use a simple #[derive(FromLua)] macro (requires feature = "macros"):
#[derive(Clone, Copy, mlua::FromLua)]
struct MyUserData(i32);
T is not required to implement UserData because of the new relaxed restrictions on userdata types.
- Minimal Luau updated to 0.588
Added #[derive(FromLua)] macro to opt-in into FromLua where T: 'static + Clone (userdata type).
#[derive(FromLua)] macro to opt-in into FromLua<T> where T: 'static + Clone (userdata type).module and vendored features are now mutually exclusiveC-unwind ABI (Rust 1.71+)AsChunk trait to support capturing wrapped Lua typesTable::sequence_values() iterator no longer uses any metamethods (Table::raw_sequence_values() is deprecated)
UserDataMethods::add_async_method() takes &T instead of cloning TPartialEq<[T]> for tablesluau-vector4 feature)Table::sequence_values() iterator no longer uses any metamethods (Table::raw_sequence_values() is deprecated)Table:is_empty() function that checks both hash and array partsffi (mlua-sys) crate for easier writing of unsafe code&str as function name in TableExt and AnyUserDataExt traitsskip_memory_check to improve performanceAnyUserData::wrap() to provide more easy way of creating any userdata in LuaOverwrite error context when called multiple times
OwnedAnyUserData::take()DeserializeOwnedluau-jit to enable (experimental) Luau codegen backend__name field in userdata metatableValue::to_string() method similar to luaL_tolstringUserDataFields::add_field() method to add static fields to UserDataBreaking changes:
Table instead of Value in Chunks.AsChunk::env() renamed to AsChunk::environment()Added Thread::set_hook() function to set hook on threads
New features:
Thread::set_hook() function to set hook on threadsValue and Tablemlua-sys crateBreaking changes:
HookTriggers (make it const)Owned Lua types (unstable feature flag)
New features:
Function::wrap/Function::wrap_mut/Function::wrap_asyncLua::register_userdata_type() to register a custom userdata types (without requiring UserData trait)Lua::create_any_userdata()create_userdata_ref/create_userdata_ref_mut for scopesAnyUserDataExt trait with auxiliary functions for AnyUserDataUserDataRef and UserDataRefMut type wrapped that implement FromLuaError::BadArgument to help identify bad argument position or nameErrorContext extension trait to attach additional context to ErrorBreaking changes:
AsChunk traitToLua/ToLuaMulti renamed to IntoLua/IntoLuaMultito_lua_err to into_lua_errFromLua impl for T: UserData+CloneLua::async_scope&Lua arg to Luau interrupt callbackOther:
Lua::from_value() methodTable::clear() methodError::downcast_ref() method#[lua_module(name = "...")] macroUpdate to Luau 0.590 (luau0-src to 0.7.x)
Update minimal (vendored) Lua 5.4 to 5.4.6
lua_closethread instead of lua_resetthread in vendored mode (Lua 5.4.6)()) or unit struct.Fix potential deadlock when trying to reuse dropped registry keys.
Minimum Luau updated to 0.555 (LUAI_MAXCSTACK limit increased to 100000)
LUAI_MAXCSTACK limit increased to 100000)_VERSION in Luau now includes version numberDebugNames in Debug::names() and DebugSource in Debug::source()MultiValue::get()Fixed bug when recycled Registry slot can be set to Nil
Fixed potential unsoundness when using Layout::from_size_align_unchecked and Rust 1.65+
Layout::from_size_align_unchecked and Rust 1.65+get/set/len methods without metatablepush/pop/raw_push/raw_pop to TableLua::load- Minimal Luau updated to 0.548
Close to-be-closed variables for Lua 5.4 when using call_async functions
Performance optimizations in handling UserData
Function::bind when passing empty binds and no arguments (#189)Added Lua::create_proxy for accessing to UserData static fields and functions without instance
Lua::create_proxy for accessing to UserData static fields and functions without instanceTable::to_pointer() and String::to_pointer() functionsAdded async support to __index and __newindex metamethods
Changes since 0.7.4
__index and __newindex metamethodsFunction::info() to get information about functions (#149).parking_lot dependency under feature flag (for UserData)Hash implementation for Lua StringValue::to_pointer() functionBreaking changes:
AsChunk trait (added implementation for Path and PathBuf).Lua sources no longer needed to build modules
__iter metamethod for LuauValue::to_pointer() functionFunction::coverage for Luau to obtain coverage reportRefactored AsChunk trait (breaking changes). AsChunk now implemented for Path and PathBuf to load lua files from fs.
&Lua from Lua::set_interrupt as it's not safe (introduced in v0.8.0-beta.3)Lua::gc_inc for Luaudebug module marked as safe (enabled by default)Hash for Lua Stringcollectgarbage for LuauAsChunk trait (breaking changes).
AsChunk now implemented for Path and PathBuf to load lua files from fs.parking_lot dependency and feature flag (for UserData)Function::info() to get information about functions (#149).More Luau compiler options (mutable globals)
- Luau vector datatype support - Luau readonly table attribute - Other Luau improvements
Refactored ffi module. C glue is no longer required
__index and __newindex metamethodsImproved Lua::create_registry_value to reuse previously expired registry keys. No need to call Lua::expire_registry_values when creating/dropping regi
Lua::create_registry_value to reuse previously expired registry keys.
No need to call Lua::expire_registry_values when creating/dropping registry values.Lua::replace_registry_value to change value of an existing Registry KeyFixed cross-compilation issue (introduced in 84a174c)
Allow pkg-config to omit include paths if they equals to standard (#114).
pkg-config to omit include paths if they equals to standard (#114).Fixed traceback generation for errors
Lua::into_static/from_static methods have been removed from the docs and are discouraged for useOne column per quarter.