pub struct Lua { /* private fields */ }Expand description
Top level Lua struct which represents an instance of Lua VM.
Implementations§
Source§impl Lua
impl Lua
Sourcepub unsafe fn unsafe_new() -> Lua
pub unsafe fn unsafe_new() -> Lua
Creates a new Lua state and loads all the standard libraries.
§Safety
The created Lua state will not have safety guarantees and will allow to load C modules.
Sourcepub fn new_with(libs: StdLib, options: LuaOptions) -> Result<Lua>
pub fn new_with(libs: StdLib, options: LuaOptions) -> Result<Lua>
Creates a new Lua state and loads the specified safe subset of the standard libraries.
Use the StdLib flags to specify the libraries you want to load.
§Safety
The created Lua state will have some safety guarantees and will not allow to load unsafe standard libraries or C modules.
See StdLib documentation for a list of unsafe modules that cannot be loaded.
Sourcepub unsafe fn unsafe_new_with(libs: StdLib, options: LuaOptions) -> Lua
pub unsafe fn unsafe_new_with(libs: StdLib, options: LuaOptions) -> Lua
Sourcepub unsafe fn get_or_init_from_ptr<'a>(state: *mut lua_State) -> &'a Lua
pub unsafe fn get_or_init_from_ptr<'a>(state: *mut lua_State) -> &'a Lua
Returns or constructs Lua instance from a raw state.
Once initialized, the returned Lua instance is cached in the registry and can be retrieved by calling this function again.
§Safety
The Lua must outlive the chosen lifetime 'a.
Sourcepub unsafe fn exec_raw<R: FromLuaMulti>(
&self,
args: impl IntoLuaMulti,
f: impl FnOnce(*mut lua_State),
) -> Result<R>
pub unsafe fn exec_raw<R: FromLuaMulti>( &self, args: impl IntoLuaMulti, f: impl FnOnce(*mut lua_State), ) -> Result<R>
Calls provided function passing a raw lua state.
The arguments will be pushed onto the stack before calling the function.
This method ensures that the Lua instance is locked while the function is called and restores Lua stack after the function returns.
§Example
let lua = Lua::new();
let n: i32 = unsafe {
let nums = (3, 4, 5);
lua.exec_raw(nums, |state| {
let n = ffi::lua_gettop(state);
let mut sum = 0;
for i in 1..=n {
sum += ffi::lua_tointeger(state, i);
}
ffi::lua_pop(state, n);
ffi::lua_pushinteger(state, sum);
})
}?;
assert_eq!(n, 12);Sourcepub fn load_std_libs(&self, libs: StdLib) -> Result<()>
pub fn load_std_libs(&self, libs: StdLib) -> Result<()>
Loads the specified subset of the standard libraries into an existing Lua state.
Use the StdLib flags to specify the libraries you want to load.
Sourcepub fn register_module(&self, modname: &str, value: impl IntoLua) -> Result<()>
pub fn register_module(&self, modname: &str, value: impl IntoLua) -> Result<()>
Registers module into an existing Lua state using the specified value.
After registration, the given value will always be immediately returned when the given module is required.
Sourcepub fn preload_module(&self, modname: &str, func: Function) -> Result<()>
Available on non-crate feature luau only.
pub fn preload_module(&self, modname: &str, func: Function) -> Result<()>
luau only.Preloads module into an existing Lua state using the specified loader function.
When the module is required, the loader function will be called with module name as the first argument.
This is similar to setting the [package.preload[modname]] field.
[package.preload[modname]]: https://www.lua.org/manual/5.4/manual.html#pdf-package.preload
Sourcepub fn unload_module(&self, modname: &str) -> Result<()>
pub fn unload_module(&self, modname: &str) -> Result<()>
Unloads module modname.
This method does not support unloading binary Lua modules since they are internally cached and can be unloaded only by closing Lua state.
This is similar to calling Lua::register_module with Nil value.
Sourcepub fn sandbox(&self, enabled: bool) -> Result<()>
Available on crate feature luau only.
pub fn sandbox(&self, enabled: bool) -> Result<()>
luau only.Enables (or disables) sandbox mode on this Lua instance.
This method, in particular:
- Set all libraries to read-only
- Set all builtin metatables to read-only
- Set globals to read-only (and activates safeenv)
- Setup local environment table that performs writes locally and proxies reads to the global environment.
- Allow only
countmode incollectgarbagefunction.
§Examples
let lua = Lua::new();
lua.sandbox(true)?;
lua.load("var = 123").exec()?;
assert_eq!(lua.globals().get::<u32>("var")?, 123);
// Restore the global environment (clear changes made in sandbox)
lua.sandbox(false)?;
assert_eq!(lua.globals().get::<Option<u32>>("var")?, None);
Sourcepub fn set_global_hook<F>(
&self,
triggers: HookTriggers,
callback: F,
) -> Result<()>
Available on non-crate feature luau only.
pub fn set_global_hook<F>( &self, triggers: HookTriggers, callback: F, ) -> Result<()>
luau only.Sets or replaces a global hook function that will periodically be called as Lua code executes.
All new threads created (by mlua) after this call will use the global hook function.
For more information see Lua::set_hook.
Sourcepub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
Available on non-crate feature luau only.
pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
luau only.Sets a hook function that will periodically be called as Lua code executes.
When exactly the hook function is called depends on the contents of the triggers
parameter, see HookTriggers for more details.
The provided hook function can error, and this error will be propagated through the Lua code
that was executing at the time the hook was triggered. This can be used to implement a
limited form of execution limits by setting HookTriggers.every_nth_instruction and
erroring once an instruction limit has been reached.
This method sets a hook function for the current thread of this Lua instance.
If you want to set a hook function for another thread (coroutine), use
Thread::set_hook instead.
§Example
Shows each line number of code being executed by the Lua interpreter.
let lua = Lua::new();
lua.set_hook(HookTriggers::EVERY_LINE, |_lua, debug| {
println!("line {:?}", debug.current_line());
Ok(VmState::Continue)
});
lua.load(r#"
local x = 2 + 3
local y = x * 63
local z = string.len(x..", "..y)
"#).exec()Sourcepub fn remove_global_hook(&self)
Available on non-crate feature luau only.
pub fn remove_global_hook(&self)
luau only.Removes a global hook previously set by Lua::set_global_hook.
This function has no effect if a hook was not previously set.
Sourcepub fn remove_hook(&self)
Available on non-crate feature luau only.
pub fn remove_hook(&self)
luau only.Removes any hook from the current thread.
This function has no effect if a hook was not previously set.
Sourcepub fn set_interrupt<F>(&self, callback: F)
Available on crate feature luau only.
pub fn set_interrupt<F>(&self, callback: F)
luau only.Sets an interrupt function that will periodically be called by Luau VM.
Any Luau code is guaranteed to call this handler “eventually”
(in practice this can happen at any function call or at any loop iteration).
This is similar to Lua::set_hook but in more simplified form.
The provided interrupt function can error, and this error will be propagated through
the Luau code that was executing at the time the interrupt was triggered.
Also this can be used to implement continuous execution limits by instructing Luau VM to
yield by returning VmState::Yield. The yield will happen only at yieldable points
of execution (not across metamethod/C-call boundaries).
§Example
Periodically yield Luau VM to suspend execution.
let lua = Lua::new();
let count = Arc::new(AtomicU64::new(0));
lua.set_interrupt(move |_| {
if count.fetch_add(1, Ordering::Relaxed) % 2 == 0 {
return Ok(VmState::Yield);
}
Ok(VmState::Continue)
});
let co = lua.create_thread(
lua.load(r#"
local b = 0
for _, x in ipairs({1, 2, 3}) do b += x end
"#)
.into_function()?,
)?;
while co.status() == ThreadStatus::Resumable {
co.resume::<()>(())?;
}
Sourcepub fn remove_interrupt(&self)
Available on crate feature luau only.
pub fn remove_interrupt(&self)
luau only.Removes any interrupt function previously set by set_interrupt.
This function has no effect if an ‘interrupt’ was not previously set.
Sourcepub fn set_thread_creation_callback<F>(&self, callback: F)
Available on crate feature luau only.
pub fn set_thread_creation_callback<F>(&self, callback: F)
luau only.Sets a thread creation callback that will be called when a thread is created.
Sourcepub fn set_thread_collection_callback<F>(&self, callback: F)
Available on crate feature luau only.
pub fn set_thread_collection_callback<F>(&self, callback: F)
luau only.Sets a thread collection callback that will be called when a thread is destroyed.
Luau GC does not support exceptions during collection, so the callback must be non-panicking. If the callback panics, the program will be aborted.
Sourcepub fn remove_thread_callbacks(&self)
Available on crate feature luau only.
pub fn remove_thread_callbacks(&self)
luau only.Removes any thread creation or collection callbacks previously set by
Lua::set_thread_creation_callback or Lua::set_thread_collection_callback.
This function has no effect if a thread callbacks were not previously set.
Sourcepub fn set_warning_function<F>(&self, callback: F)
Available on crate feature lua54 only.
pub fn set_warning_function<F>(&self, callback: F)
lua54 only.Sets the warning function to be used by Lua to emit warnings.
Sourcepub fn remove_warning_function(&self)
Available on crate feature lua54 only.
pub fn remove_warning_function(&self)
lua54 only.Removes warning function previously set by set_warning_function.
This function has no effect if a warning function was not previously set.
Sourcepub fn warning(&self, msg: impl AsRef<str>, incomplete: bool)
Available on crate feature lua54 only.
pub fn warning(&self, msg: impl AsRef<str>, incomplete: bool)
lua54 only.Emits a warning with the given message.
A message in a call with incomplete set to true should be continued in
another call to this function.
Sourcepub fn inspect_stack<R>(
&self,
level: usize,
f: impl FnOnce(&Debug<'_>) -> R,
) -> Option<R>
pub fn inspect_stack<R>( &self, level: usize, f: impl FnOnce(&Debug<'_>) -> R, ) -> Option<R>
Gets information about the interpreter runtime stack at a given level.
This function calls callback f, passing the [Debug] structure that can be used to get
information about the function executing at a given level.
Level 0 is the current running function, whereas level n+1 is the function that has
called level n (except for tail calls, which do not count in the stack).
Sourcepub fn used_memory(&self) -> usize
pub fn used_memory(&self) -> usize
Returns the amount of memory (in bytes) currently used inside this Lua state.
Sourcepub fn set_memory_limit(&self, limit: usize) -> Result<usize>
pub fn set_memory_limit(&self, limit: usize) -> Result<usize>
Sets a memory limit (in bytes) on this Lua state.
Once an allocation occurs that would pass this memory limit, a Error::MemoryError is
generated instead.
Returns previous limit (zero means no limit).
Does not work in module mode where Lua state is managed externally.
Sourcepub fn gc_is_running(&self) -> bool
Available on crate features lua54 or lua53 or lua52 or luau only.
pub fn gc_is_running(&self) -> bool
lua54 or lua53 or lua52 or luau only.Returns true if the garbage collector is currently running automatically.
Sourcepub fn gc_restart(&self)
pub fn gc_restart(&self)
Restarts the Lua GC if it is not running
Sourcepub fn gc_collect(&self) -> Result<()>
pub fn gc_collect(&self) -> Result<()>
Perform a full garbage-collection cycle.
It may be necessary to call this function twice to collect all currently unreachable objects. Once to finish the current gc cycle, and once to start and finish the next cycle.
Sourcepub fn gc_step(&self) -> Result<bool>
pub fn gc_step(&self) -> Result<bool>
Steps the garbage collector one indivisible step.
Returns true if this has finished a collection cycle.
Sourcepub fn gc_step_kbytes(&self, kbytes: c_int) -> Result<bool>
pub fn gc_step_kbytes(&self, kbytes: c_int) -> Result<bool>
Steps the garbage collector as though memory had been allocated.
if kbytes is 0, then this is the same as calling gc_step. Returns true if this step has
finished a collection cycle.
Sourcepub fn gc_set_pause(&self, pause: c_int) -> c_int
pub fn gc_set_pause(&self, pause: c_int) -> c_int
Sets the pause value of the collector.
Returns the previous value of pause. More information can be found in the Lua
documentation.
For Luau this parameter sets GC goal
Sourcepub fn gc_set_step_multiplier(&self, step_multiplier: c_int) -> c_int
pub fn gc_set_step_multiplier(&self, step_multiplier: c_int) -> c_int
Sets the step multiplier value of the collector.
Returns the previous value of the step multiplier. More information can be found in the
Lua documentation.
Sourcepub fn gc_inc(
&self,
pause: c_int,
step_multiplier: c_int,
step_size: c_int,
) -> GCMode
pub fn gc_inc( &self, pause: c_int, step_multiplier: c_int, step_size: c_int, ) -> GCMode
Changes the collector to incremental mode with the given parameters.
Returns the previous mode (always GCMode::Incremental in Lua < 5.4).
More information can be found in the Lua documentation.
Sourcepub fn gc_gen(&self, minor_multiplier: c_int, major_multiplier: c_int) -> GCMode
Available on crate feature lua54 only.
pub fn gc_gen(&self, minor_multiplier: c_int, major_multiplier: c_int) -> GCMode
lua54 only.Changes the collector to generational mode with the given parameters.
Returns the previous mode. More information about the generational GC can be found in the Lua 5.4 documentation.
Sourcepub fn set_compiler(&self, compiler: Compiler)
Available on crate feature luau only.
pub fn set_compiler(&self, compiler: Compiler)
luau only.Sets a default Luau compiler (with custom options).
This compiler will be used by default to load all Lua chunks
including via require function.
See Compiler for details and possible options.
Sourcepub fn enable_jit(&self, enable: bool)
Available on crate feature luau-jit only.
pub fn enable_jit(&self, enable: bool)
luau-jit only.Toggles JIT compilation mode for new chunks of code.
By default JIT is enabled. Changing this option does not have any effect on already loaded functions.
Sourcepub fn load<'a>(&self, chunk: impl AsChunk + 'a) -> Chunk<'a>
pub fn load<'a>(&self, chunk: impl AsChunk + 'a) -> Chunk<'a>
Returns Lua source code as a Chunk builder type.
In order to actually compile or run the resulting code, you must call Chunk::exec or
similar on the returned builder. Code is not even parsed until one of these methods is
called.
Sourcepub fn create_string(&self, s: impl AsRef<[u8]>) -> Result<String>
pub fn create_string(&self, s: impl AsRef<[u8]>) -> Result<String>
Creates and returns an interned Lua string.
Lua strings can be arbitrary [u8] data including embedded nulls, so in addition to &str
and &String, you can also pass plain &[u8] here.
Sourcepub fn create_buffer(&self, data: impl AsRef<[u8]>) -> Result<Buffer>
Available on crate feature luau only.
pub fn create_buffer(&self, data: impl AsRef<[u8]>) -> Result<Buffer>
luau only.Creates and returns a Luau buffer object from a byte slice of data.
Sourcepub fn create_buffer_with_capacity(&self, size: usize) -> Result<Buffer>
Available on crate feature luau only.
pub fn create_buffer_with_capacity(&self, size: usize) -> Result<Buffer>
luau only.Creates and returns a Luau buffer object with the specified size.
Size limit is 1GB. All bytes will be initialized to zero.
Sourcepub fn create_table(&self) -> Result<Table>
pub fn create_table(&self) -> Result<Table>
Creates and returns a new empty table.
Sourcepub fn create_table_with_capacity(
&self,
narr: usize,
nrec: usize,
) -> Result<Table>
pub fn create_table_with_capacity( &self, narr: usize, nrec: usize, ) -> Result<Table>
Creates and returns a new empty table, with the specified capacity.
narris a hint for how many elements the table will have as a sequence.nrecis a hint for how many other elements the table will have.
Lua may use these hints to preallocate memory for the new table.
Sourcepub fn create_table_from<K, V>(
&self,
iter: impl IntoIterator<Item = (K, V)>,
) -> Result<Table>
pub fn create_table_from<K, V>( &self, iter: impl IntoIterator<Item = (K, V)>, ) -> Result<Table>
Creates a table and fills it with values from an iterator.
Sourcepub fn create_sequence_from<T>(
&self,
iter: impl IntoIterator<Item = T>,
) -> Result<Table>where
T: IntoLua,
pub fn create_sequence_from<T>(
&self,
iter: impl IntoIterator<Item = T>,
) -> Result<Table>where
T: IntoLua,
Creates a table from an iterator of values, using 1.. as the keys.
Sourcepub fn create_function<F, A, R>(&self, func: F) -> Result<Function>
pub fn create_function<F, A, R>(&self, func: F) -> Result<Function>
Wraps a Rust function or closure, creating a callable Lua function handle to it.
The function’s return value is always a Result: If the function returns Err, the error
is raised as a Lua error, which can be caught using (x)pcall or bubble up to the Rust code
that invoked the Lua code. This allows using the ? operator to propagate errors through
intermediate Lua code.
If the function returns Ok, the contained value will be converted to one or more Lua
values. For details on Rust-to-Lua conversions, refer to the IntoLua and
IntoLuaMulti traits.
§Examples
Create a function which prints its argument:
let greet = lua.create_function(|_, name: String| {
println!("Hello, {}!", name);
Ok(())
});Use tuples to accept multiple arguments:
let print_person = lua.create_function(|_, (name, age): (String, u8)| {
println!("{} is {} years old!", name, age);
Ok(())
});Sourcepub fn create_function_mut<F, A, R>(&self, func: F) -> Result<Function>
pub fn create_function_mut<F, A, R>(&self, func: F) -> Result<Function>
Wraps a Rust mutable closure, creating a callable Lua function handle to it.
This is a version of Lua::create_function that accepts a FnMut argument.
Sourcepub unsafe fn create_c_function(&self, func: lua_CFunction) -> Result<Function>
pub unsafe fn create_c_function(&self, func: lua_CFunction) -> Result<Function>
Wraps a C function, creating a callable Lua function handle to it.
§Safety
This function is unsafe because provides a way to execute unsafe C function.
Sourcepub fn create_async_function<F, A, FR, R>(&self, func: F) -> Result<Function>where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
FR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
Available on crate feature async only.
pub fn create_async_function<F, A, FR, R>(&self, func: F) -> Result<Function>where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
FR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
async only.Wraps a Rust async function or closure, creating a callable Lua function handle to it.
While executing the function Rust will poll the Future and if the result is not ready,
call yield() passing internal representation of a Poll::Pending value.
The function must be called inside Lua coroutine (Thread) to be able to suspend its
execution. An executor should be used to poll AsyncThread and mlua will take a provided
Waker in that case. Otherwise noop waker will be used if try to call the function outside of
Rust executors.
The family of call_async() functions takes care about creating Thread.
§Examples
Non blocking sleep:
use std::time::Duration;
use mlua::{Lua, Result};
async fn sleep(_lua: Lua, n: u64) -> Result<&'static str> {
tokio::time::sleep(Duration::from_millis(n)).await;
Ok("done")
}
#[tokio::main]
async fn main() -> Result<()> {
let lua = Lua::new();
lua.globals().set("sleep", lua.create_async_function(sleep)?)?;
let res: String = lua.load("return sleep(...)").call_async(100).await?; // Sleep 100ms
assert_eq!(res, "done");
Ok(())
}Sourcepub fn create_thread(&self, func: Function) -> Result<Thread>
pub fn create_thread(&self, func: Function) -> Result<Thread>
Wraps a Lua function into a new thread (or coroutine).
Equivalent to coroutine.create.
Sourcepub fn create_userdata<T>(&self, data: T) -> Result<AnyUserData>
pub fn create_userdata<T>(&self, data: T) -> Result<AnyUserData>
Creates a Lua userdata object from a custom userdata type.
All userdata instances of the same type T shares the same metatable.
Sourcepub fn create_ser_userdata<T>(&self, data: T) -> Result<AnyUserData>
Available on crate feature serde only.
pub fn create_ser_userdata<T>(&self, data: T) -> Result<AnyUserData>
serde only.Creates a Lua userdata object from a custom serializable userdata type.
Sourcepub fn create_any_userdata<T>(&self, data: T) -> Result<AnyUserData>where
T: MaybeSend + 'static,
pub fn create_any_userdata<T>(&self, data: T) -> Result<AnyUserData>where
T: MaybeSend + 'static,
Creates a Lua userdata object from a custom Rust type.
You can register the type using Lua::register_userdata_type to add fields or methods
before calling this method.
Otherwise, the userdata object will have an empty metatable.
All userdata instances of the same type T shares the same metatable.
Sourcepub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
Available on crate feature serde only.
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData>
serde only.Creates a Lua userdata object from a custom serializable Rust type.
See Lua::create_any_userdata for more details.
Sourcepub fn register_userdata_type<T: 'static>(
&self,
f: impl FnOnce(&mut UserDataRegistry<T>),
) -> Result<()>
pub fn register_userdata_type<T: 'static>( &self, f: impl FnOnce(&mut UserDataRegistry<T>), ) -> Result<()>
Registers a custom Rust type in Lua to use in userdata objects.
This methods provides a way to add fields or methods to userdata objects of a type T.
Sourcepub fn create_proxy<T>(&self) -> Result<AnyUserData>where
T: UserData + 'static,
pub fn create_proxy<T>(&self) -> Result<AnyUserData>where
T: UserData + 'static,
Create a Lua userdata “proxy” object from a custom userdata type.
Proxy object is an empty userdata object that has T metatable attached.
The main purpose of this object is to provide access to static fields and functions
without creating an instance of type T.
You can get or set uservalues on this object but you cannot borrow any Rust type.
§Examples
struct MyUserData(i32);
impl UserData for MyUserData {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("val", |_, this| Ok(this.0));
}
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_function("new", |_, value: i32| Ok(MyUserData(value)));
}
}
lua.globals().set("MyUserData", lua.create_proxy::<MyUserData>()?)?;
lua.load("assert(MyUserData.new(321).val == 321)").exec()?;Sourcepub fn set_type_metatable<T: LuaType>(&self, metatable: Option<Table>)
pub fn set_type_metatable<T: LuaType>(&self, metatable: Option<Table>)
Sets the metatable for a Lua builtin type.
The metatable will be shared by all values of the given type.
§Examples
Change metatable for Lua boolean type:
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()?;Sourcepub fn set_globals(&self, globals: Table) -> Result<()>
pub fn set_globals(&self, globals: Table) -> Result<()>
Sets the global environment.
This will replace the current global environment with the provided globals table.
For Lua 5.2+ the globals table is stored in the registry and shared between all threads. For Lua 5.1 and Luau the globals table is stored in each thread.
Please note that any existing Lua functions have cached global environment and will not
see the changes made by this method.
To update the environment for existing Lua functions, use Function::set_environment.
Sourcepub fn current_thread(&self) -> Thread
pub fn current_thread(&self) -> Thread
Returns a handle to the active Thread.
For calls to Lua this will be the main Lua thread, for parameters given to a callback,
this will be whatever Lua thread called the callback.
Sourcepub fn scope<'env, R>(
&self,
f: impl for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> Result<R>,
) -> Result<R>
pub fn scope<'env, R>( &self, f: impl for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> Result<R>, ) -> Result<R>
Calls the given function with a Scope parameter, giving the function the ability to
create userdata and callbacks from Rust types that are !Send or non-'static.
The lifetime of any function or userdata created through Scope lasts only until the
completion of this method call, on completion all such created values are automatically
dropped and Lua references to them are invalidated. If a script accesses a value created
through Scope outside of this method, a Lua error will result. Since we can ensure the
lifetime of values created through Scope, and we know that Lua cannot be sent to
another thread while Scope is live, it is safe to allow !Send data types and whose
lifetimes only outlive the scope lifetime.
Sourcepub fn coerce_string(&self, v: Value) -> Result<Option<String>>
pub fn coerce_string(&self, v: Value) -> Result<Option<String>>
Attempts to coerce a Lua value into a String in a manner consistent with Lua’s internal behavior.
To succeed, the value must be a string (in which case this is a no-op), an integer, or a number.
Sourcepub fn coerce_integer(&self, v: Value) -> Result<Option<Integer>>
pub fn coerce_integer(&self, v: Value) -> Result<Option<Integer>>
Attempts to coerce a Lua value into an integer in a manner consistent with Lua’s internal behavior.
To succeed, the value must be an integer, a floating point number that has an exact representation as an integer, or a string that can be converted to an integer. Refer to the Lua manual for details.
Sourcepub fn coerce_number(&self, v: Value) -> Result<Option<Number>>
pub fn coerce_number(&self, v: Value) -> Result<Option<Number>>
Attempts to coerce a Lua value into a Number in a manner consistent with Lua’s internal behavior.
To succeed, the value must be a number or a string that can be converted to a number. Refer to the Lua manual for details.
Sourcepub fn pack_multi(&self, t: impl IntoLuaMulti) -> Result<MultiValue>
pub fn pack_multi(&self, t: impl IntoLuaMulti) -> Result<MultiValue>
Converts a value that implements IntoLuaMulti into a MultiValue instance.
Sourcepub fn unpack_multi<T: FromLuaMulti>(&self, value: MultiValue) -> Result<T>
pub fn unpack_multi<T: FromLuaMulti>(&self, value: MultiValue) -> Result<T>
Converts a MultiValue instance into a value that implements FromLuaMulti.
Sourcepub fn set_named_registry_value(&self, key: &str, t: impl IntoLua) -> Result<()>
pub fn set_named_registry_value(&self, key: &str, t: impl IntoLua) -> Result<()>
Set a value in the Lua registry based on a string key.
This value will be available to Rust from all Lua instances which share the same main state.
Sourcepub fn named_registry_value<T>(&self, key: &str) -> Result<T>where
T: FromLua,
pub fn named_registry_value<T>(&self, key: &str) -> Result<T>where
T: FromLua,
Get a value from the Lua registry based on a string key.
Any Lua instance which shares the underlying main state may call this method to
get a value previously set by Lua::set_named_registry_value.
Sourcepub fn unset_named_registry_value(&self, key: &str) -> Result<()>
pub fn unset_named_registry_value(&self, key: &str) -> Result<()>
Removes a named value in the Lua registry.
Equivalent to calling Lua::set_named_registry_value with a value of Nil.
Sourcepub fn create_registry_value(&self, t: impl IntoLua) -> Result<RegistryKey>
pub fn create_registry_value(&self, t: impl IntoLua) -> Result<RegistryKey>
Place a value in the Lua registry with an auto-generated key.
This value will be available to Rust from all Lua instances which share the same main state.
Be warned, garbage collection of values held inside the registry is not automatic, see
RegistryKey for more details.
However, dropped RegistryKeys automatically reused to store new values.
Sourcepub fn registry_value<T: FromLua>(&self, key: &RegistryKey) -> Result<T>
pub fn registry_value<T: FromLua>(&self, key: &RegistryKey) -> Result<T>
Get a value from the Lua registry by its RegistryKey
Any Lua instance which shares the underlying main state may call this method to get a value
previously placed by Lua::create_registry_value.
Sourcepub fn remove_registry_value(&self, key: RegistryKey) -> Result<()>
pub fn remove_registry_value(&self, key: RegistryKey) -> Result<()>
Removes a value from the Lua registry.
You may call this function to manually remove a value placed in the registry with
Lua::create_registry_value. In addition to manual RegistryKey removal, you can also
call Lua::expire_registry_values to automatically remove values from the registry
whose RegistryKeys have been dropped.
Sourcepub fn replace_registry_value(
&self,
key: &mut RegistryKey,
t: impl IntoLua,
) -> Result<()>
pub fn replace_registry_value( &self, key: &mut RegistryKey, t: impl IntoLua, ) -> Result<()>
Replaces a value in the Lua registry by its RegistryKey.
An identifier used in RegistryKey may possibly be changed to a new value.
See Lua::create_registry_value for more details.
Sourcepub fn owns_registry_value(&self, key: &RegistryKey) -> bool
pub fn owns_registry_value(&self, key: &RegistryKey) -> bool
Returns true if the given RegistryKey was created by a Lua which shares the
underlying main state with this Lua instance.
Other than this, methods that accept a RegistryKey will return
Error::MismatchedRegistryKey if passed a RegistryKey that was not created with a
matching Lua state.
Sourcepub fn expire_registry_values(&self)
pub fn expire_registry_values(&self)
Remove any registry values whose RegistryKeys have all been dropped.
Unlike normal handle values, RegistryKeys do not automatically remove themselves on
Drop, but you can call this method to remove any unreachable registry values not
manually removed by Lua::remove_registry_value.
Sourcepub fn set_app_data<T: MaybeSend + 'static>(&self, data: T) -> Option<T>
pub fn set_app_data<T: MaybeSend + 'static>(&self, data: T) -> Option<T>
Sets or replaces an application data object of type T.
Application data could be accessed at any time by using Lua::app_data_ref or
Lua::app_data_mut methods where T is the data type.
§Panics
Panics if the app data container is currently borrowed.
§Examples
use mlua::{Lua, Result};
fn hello(lua: &Lua, _: ()) -> Result<()> {
let mut s = lua.app_data_mut::<&str>().unwrap();
assert_eq!(*s, "hello");
*s = "world";
Ok(())
}
fn main() -> Result<()> {
let lua = Lua::new();
lua.set_app_data("hello");
lua.create_function(hello)?.call::<()>(())?;
let s = lua.app_data_ref::<&str>().unwrap();
assert_eq!(*s, "world");
Ok(())
}Sourcepub fn try_set_app_data<T: MaybeSend + 'static>(
&self,
data: T,
) -> StdResult<Option<T>, T>
pub fn try_set_app_data<T: MaybeSend + 'static>( &self, data: T, ) -> StdResult<Option<T>, T>
Tries to set or replace an application data object of type T.
Returns:
Ok(Some(old_data))if the data object of typeTwas successfully replaced.Ok(None)if the data object of typeTwas successfully inserted.Err(data)if the data object of typeTwas not inserted because the container is currently borrowed.
See Lua::set_app_data for examples.
Sourcepub fn app_data_ref<T: 'static>(&self) -> Option<AppDataRef<'_, T>>
pub fn app_data_ref<T: 'static>(&self) -> Option<AppDataRef<'_, T>>
Gets a reference to an application data object stored by Lua::set_app_data of type
T.
§Panics
Panics if the data object of type T is currently mutably borrowed. Multiple immutable
reads can be taken out at the same time.
Sourcepub fn try_app_data_ref<T: 'static>(
&self,
) -> StdResult<Option<AppDataRef<'_, T>>, BorrowError>
pub fn try_app_data_ref<T: 'static>( &self, ) -> StdResult<Option<AppDataRef<'_, T>>, BorrowError>
Tries to get a reference to an application data object stored by Lua::set_app_data of
type T.
Sourcepub fn app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<'_, T>>
pub fn app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<'_, T>>
Gets a mutable reference to an application data object stored by Lua::set_app_data of
type T.
§Panics
Panics if the data object of type T is currently borrowed.
Sourcepub fn try_app_data_mut<T: 'static>(
&self,
) -> StdResult<Option<AppDataRefMut<'_, T>>, BorrowMutError>
pub fn try_app_data_mut<T: 'static>( &self, ) -> StdResult<Option<AppDataRefMut<'_, T>>, BorrowMutError>
Tries to get a mutable reference to an application data object stored by
Lua::set_app_data of type T.
Sourcepub fn remove_app_data<T: 'static>(&self) -> Option<T>
pub fn remove_app_data<T: 'static>(&self) -> Option<T>
Removes an application data of type T.
§Panics
Panics if the app data container is currently borrowed.
Sourcepub async fn yield_with<R: FromLuaMulti>(
&self,
args: impl IntoLuaMulti,
) -> Result<R>
Available on crate feature async only.
pub async fn yield_with<R: FromLuaMulti>( &self, args: impl IntoLuaMulti, ) -> Result<R>
async only.Suspends the current async function, returning the provided arguments to caller.
This function is similar to coroutine.yield but allow yeilding Rust functions
and passing values to the caller.
Please note that you cannot cross Thread boundaries (e.g. calling yield_with on one
thread and resuming on another).
§Examples
Async iterator:
async fn generator(lua: Lua, _: ()) -> Result<()> {
for i in 0..10 {
lua.yield_with::<()>(i).await?;
}
Ok(())
}
fn main() -> Result<()> {
let lua = Lua::new();
lua.globals().set("generator", lua.create_async_function(generator)?)?;
lua.load(r#"
local n = 0
for i in coroutine.wrap(generator) do
n = n + i
end
assert(n == 45)
"#)
.exec()
}Exchange values on yield:
async fn pingpong(lua: Lua, mut val: i32) -> Result<()> {
loop {
val = lua.yield_with::<i32>(val).await? + 1;
}
Ok(())
}
let lua = Lua::new();
let co = lua.create_thread(lua.create_async_function(pingpong)?)?;
assert_eq!(co.resume::<i32>(1)?, 1);
assert_eq!(co.resume::<i32>(2)?, 3);
assert_eq!(co.resume::<i32>(3)?, 4);
Trait Implementations§
Source§impl LuaSerdeExt for Lua
Available on crate feature serde only.
impl LuaSerdeExt for Lua
serde only.Source§fn null(&self) -> Value
fn null(&self) -> Value
Source§fn array_metatable(&self) -> Table
fn array_metatable(&self) -> Table
# operator on that table. Read moreSource§fn from_value<T>(&self, value: Value) -> Result<T>where
T: DeserializeOwned,
fn from_value<T>(&self, value: Value) -> Result<T>where
T: DeserializeOwned,
Source§fn from_value_with<T>(&self, value: Value, options: Options) -> Result<T>where
T: DeserializeOwned,
fn from_value_with<T>(&self, value: Value, options: Options) -> Result<T>where
T: DeserializeOwned,
Auto Trait Implementations§
impl Freeze for Lua
impl !RefUnwindSafe for Lua
impl Send for Lua
impl Sync for Lua
impl Unpin for Lua
impl !UnwindSafe for Lua
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more