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 would not have safety guarantees and would 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 would have some safety guarantees and would 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 init_from_ptr(state: *mut lua_State) -> Lua
pub unsafe fn init_from_ptr(state: *mut lua_State) -> Lua
Constructs a new Lua instance from an existing raw state.
Once called, a returned Lua state is cached in the registry and can be retrieved by calling this function again.
sourcepub fn load_from_std_lib(&self, libs: StdLib) -> Result<()>
pub fn load_from_std_lib(&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 load_from_function<'lua, T>(
&'lua self,
modname: &str,
func: Function<'lua>
) -> Result<T>where
T: FromLua<'lua>,
pub fn load_from_function<'lua, T>(
&'lua self,
modname: &str,
func: Function<'lua>
) -> Result<T>where
T: FromLua<'lua>,
Loads module modname
into an existing Lua state using the specified entrypoint
function.
Internally calls the Lua function func
with the string modname
as an argument,
sets the call result to package.loaded[modname]
and returns copy of the result.
If package.loaded[modname]
value is not nil, returns copy of the value without
calling the function.
If the function does not return a non-nil value then this method assigns true to
package.loaded[modname]
.
Behavior is similar to Lua’s require
function.
sourcepub fn unload(&self, modname: &str) -> Result<()>
pub fn unload(&self, modname: &str) -> Result<()>
Unloads module modname
.
Removes module from the package.loaded
table which allows to load it again.
It does not support unloading binary Lua modules since they are internally cached and can be
unloaded only by closing Lua state.
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.
§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);
Requires feature = "luau"
sourcepub fn set_hook<F>(&self, triggers: HookTriggers, callback: F)
Available on non-crate feature luau
only.
pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F)
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.
Please note you cannot have more than one hook function set at a time for this Lua instance.
§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.curr_line());
Ok(())
});
lua.load(r#"
local x = 2 + 3
local y = x * 63
local z = string.len(x..", "..y)
"#).exec()
sourcepub fn remove_hook(&self)
Available on non-crate feature luau
only.
pub fn remove_hook(&self)
luau
only.Removes any hook previously set by Lua::set_hook()
or Thread::set_hook()
.
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).
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
.
This is similar to Lua::set_hook
but in more simplified form.
§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’ previously set by set_interrupt
.
This function has no effect if an ‘interrupt’ was 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.
Requires feature = "lua54"
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.
Requires feature = "lua54"
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.
Requires feature = "lua54"
sourcepub fn inspect_stack(&self, level: usize) -> Option<Debug<'_>>
pub fn inspect_stack(&self, level: usize) -> Option<Debug<'_>>
Gets information about the interpreter runtime stack.
This function returns 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
pub fn gc_is_running(&self) -> bool
Returns true if the garbage collector is currently running automatically.
Requires feature = "lua54/lua53/lua52/luau"
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.
Requires feature = "lua54"
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.
Requires feature = "luau"
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<'lua, 'a>(
&'lua self,
chunk: impl AsChunk<'lua, 'a>
) -> Chunk<'lua, 'a>
pub fn load<'lua, 'a>( &'lua self, chunk: impl AsChunk<'lua, 'a> ) -> Chunk<'lua, '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<'_>>
Create and return 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_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.
narr
is a hint for how many elements the table will have as a sequence;
nrec
is 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<'lua, K, V, I>(
&'lua self,
iter: I
) -> Result<Table<'lua>>
pub fn create_table_from<'lua, K, V, I>( &'lua self, iter: I ) -> Result<Table<'lua>>
Creates a table and fills it with values from an iterator.
sourcepub fn create_sequence_from<'lua, T, I>(
&'lua self,
iter: I
) -> Result<Table<'lua>>where
T: IntoLua<'lua>,
I: IntoIterator<Item = T>,
pub fn create_sequence_from<'lua, T, I>(
&'lua self,
iter: I
) -> Result<Table<'lua>>where
T: IntoLua<'lua>,
I: IntoIterator<Item = T>,
Creates a table from an iterator of values, using 1..
as the keys.
sourcepub fn create_function<'lua, A, R, F>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: Fn(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
pub fn create_function<'lua, A, R, F>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: Fn(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
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<'lua, A, R, F>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: FnMut(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
pub fn create_function_mut<'lua, A, R, F>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: FnMut(&'lua Lua, A) -> Result<R> + MaybeSend + 'static,
Wraps a Rust mutable closure, creating a callable Lua function handle to it.
This is a version of create_function
that accepts a FnMut argument. Refer to
create_function
for more information about the implementation.
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<'lua, A, R, F, FR>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: Fn(&'lua Lua, A) -> FR + MaybeSend + 'static,
FR: Future<Output = Result<R>> + 'lua,
Available on crate feature async
only.
pub fn create_async_function<'lua, A, R, F, FR>(
&'lua self,
func: F
) -> Result<Function<'lua>>where
A: FromLuaMulti<'lua>,
R: IntoLuaMulti<'lua>,
F: Fn(&'lua Lua, A) -> FR + MaybeSend + 'static,
FR: Future<Output = Result<R>> + 'lua,
async
only.Wraps a Rust async function or closure, creating a callable Lua function handle to it.
While executing the function Rust will poll 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
.
Requires feature = "async"
§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<'lua>(
&'lua self,
func: Function<'_>
) -> Result<Thread<'lua>>
pub fn create_thread<'lua>( &'lua self, func: Function<'_> ) -> Result<Thread<'lua>>
Wraps a Lua function into a new thread (or coroutine).
Equivalent to coroutine.create
.
sourcepub fn create_userdata<T>(&self, data: T) -> Result<AnyUserData<'_>>where
T: UserData + MaybeSend + 'static,
pub fn create_userdata<T>(&self, data: T) -> Result<AnyUserData<'_>>where
T: UserData + MaybeSend + 'static,
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 serialize
only.
pub fn create_ser_userdata<T>(&self, data: T) -> Result<AnyUserData<'_>>
serialize
only.Creates a Lua userdata object from a custom serializable userdata type.
Requires feature = "serialize"
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<'_>>where
T: Serialize + MaybeSend + 'static,
Available on crate feature serialize
only.
pub fn create_ser_any_userdata<T>(&self, data: T) -> Result<AnyUserData<'_>>where
T: Serialize + MaybeSend + 'static,
serialize
only.Creates a Lua userdata object from a custom serializable Rust type.
See Lua::create_any_userdata()
for more details.
Requires feature = "serialize"
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<'lua, F: UserDataFields<'lua, Self>>(fields: &mut F) {
fields.add_field_method_get("val", |_, this| Ok(this.0));
}
fn add_methods<'lua, M: UserDataMethods<'lua, 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_vector_metatable(&self, metatable: Option<Table<'_>>)
Available on crate features luau
and unstable
only.
pub fn set_vector_metatable(&self, metatable: Option<Table<'_>>)
luau
and unstable
only.Sets the metatable for a Luau builtin vector type.
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<'lua, 'scope, R>(
&'lua self,
f: impl FnOnce(&Scope<'lua, 'scope>) -> Result<R>
) -> Result<R>where
'lua: 'scope,
pub fn scope<'lua, 'scope, R>(
&'lua self,
f: impl FnOnce(&Scope<'lua, 'scope>) -> Result<R>
) -> Result<R>where
'lua: 'scope,
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 datatypes and whose lifetimes only
outlive the scope lifetime.
Inside the scope callback, all handles created through Scope will share the same unique ’lua
lifetime of the parent Lua
. This allows scoped and non-scoped values to be mixed in
API calls, which is very useful (e.g. passing a scoped userdata to a non-scoped function).
However, this also enables handles to scoped values to be trivially leaked from the given
callback. This is not dangerous, though! After the callback returns, all scoped values are
invalidated, which means that though references may exist, the Rust types backing them have
dropped. Function
types will error when called, and AnyUserData
will be typeless. It
would be impossible to prevent handles to scoped values from escaping anyway, since you
would always be able to smuggle them through Lua state.
sourcepub fn coerce_string<'lua>(
&'lua self,
v: Value<'lua>
) -> Result<Option<String<'lua>>>
pub fn coerce_string<'lua>( &'lua self, v: Value<'lua> ) -> Result<Option<String<'lua>>>
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<'lua, T: IntoLua<'lua>>(&'lua self, t: T) -> Result<Value<'lua>>
pub fn pack<'lua, T: IntoLua<'lua>>(&'lua self, t: T) -> Result<Value<'lua>>
Converts a value that implements IntoLua
into a Value
instance.
sourcepub fn unpack<'lua, T: FromLua<'lua>>(
&'lua self,
value: Value<'lua>
) -> Result<T>
pub fn unpack<'lua, T: FromLua<'lua>>( &'lua self, value: Value<'lua> ) -> Result<T>
Converts a Value
instance into a value that implements FromLua
.
sourcepub fn pack_multi<'lua, T: IntoLuaMulti<'lua>>(
&'lua self,
t: T
) -> Result<MultiValue<'lua>>
pub fn pack_multi<'lua, T: IntoLuaMulti<'lua>>( &'lua self, t: T ) -> Result<MultiValue<'lua>>
Converts a value that implements IntoLuaMulti
into a MultiValue
instance.
sourcepub fn unpack_multi<'lua, T: FromLuaMulti<'lua>>(
&'lua self,
value: MultiValue<'lua>
) -> Result<T>
pub fn unpack_multi<'lua, T: FromLuaMulti<'lua>>( &'lua self, value: MultiValue<'lua> ) -> Result<T>
Converts a MultiValue
instance into a value that implements FromLuaMulti
.
sourcepub fn set_named_registry_value<'lua, T>(
&'lua self,
name: &str,
t: T
) -> Result<()>where
T: IntoLua<'lua>,
pub fn set_named_registry_value<'lua, T>(
&'lua self,
name: &str,
t: T
) -> Result<()>where
T: IntoLua<'lua>,
Set a value in the Lua registry based on a string name.
This value will be available to rust from all Lua
instances which share the same main
state.
sourcepub fn named_registry_value<'lua, T>(&'lua self, name: &str) -> Result<T>where
T: FromLua<'lua>,
pub fn named_registry_value<'lua, T>(&'lua self, name: &str) -> Result<T>where
T: FromLua<'lua>,
Get a value from the Lua registry based on a string name.
Any Lua instance which shares the underlying main state may call this method to
get a value previously set by set_named_registry_value
.
sourcepub fn unset_named_registry_value(&self, name: &str) -> Result<()>
pub fn unset_named_registry_value(&self, name: &str) -> Result<()>
Removes a named value in the Lua registry.
Equivalent to calling set_named_registry_value
with a value of Nil.
sourcepub fn create_registry_value<'lua, T: IntoLua<'lua>>(
&'lua self,
t: T
) -> Result<RegistryKey>
pub fn create_registry_value<'lua, T: IntoLua<'lua>>( &'lua self, t: T ) -> 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 RegistryKey
s automatically reused to store new values.
sourcepub fn registry_value<'lua, T: FromLua<'lua>>(
&'lua self,
key: &RegistryKey
) -> Result<T>
pub fn registry_value<'lua, T: FromLua<'lua>>( &'lua 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 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
create_registry_value
. In addition to manual RegistryKey
removal, you can also call
expire_registry_values
to automatically remove values from the registry whose
RegistryKey
s have been dropped.
sourcepub fn replace_registry_value<'lua, T: IntoLua<'lua>>(
&'lua self,
key: &RegistryKey,
t: T
) -> Result<()>
pub fn replace_registry_value<'lua, T: IntoLua<'lua>>( &'lua self, key: &RegistryKey, t: T ) -> Result<()>
Replaces a value in the Lua registry by its RegistryKey
.
See 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 RegistryKey
s have all been dropped.
Unlike normal handle values, RegistryKey
s 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 typeT
was successfully replaced.Ok(None)
if the data object of typeT
was successfully inserted.Err(data)
if the data object of typeT
was 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 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 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.
Trait Implementations§
source§impl LuaSerdeExt for Lua
Available on crate feature serialize
only.
impl LuaSerdeExt for Lua
serialize
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,
impl Send for Lua
send
only.Requires feature = "send"