Struct mlua::Lua

source · []
#[repr(transparent)]
pub struct Lua(_);
Expand description

Top level Lua struct which represents an instance of Lua VM.

Implementations

Creates a new Lua state and loads the safe subset of the standard libraries.

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.

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.

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.

Creates a new Lua state and loads the specified subset of the standard libraries.

Use the StdLib flags to specify the libraries you want to load.

Safety

The created Lua state will not have safety guarantees and allow to load C modules.

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.

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.

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.

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.

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"

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(())?;
}

Removes any ‘interrupt’ previously set by set_interrupt.

This function has no effect if an ‘interrupt’ was not previously set.

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).

Returns the amount of memory (in bytes) currently used inside this Lua state.

Returns true if the garbage collector is currently running automatically.

Requires feature = "lua54/lua53/lua52/luau"

Stop the Lua GC from running

Restarts the Lua GC if it is not running

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.

Steps the garbage collector one indivisible step.

Returns true if this has finished a collection cycle.

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.

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

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.

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.

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"

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.

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.

Creates and returns a new empty 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.

Creates a table and fills it with values from an iterator.

Creates a table from an iterator of values, using 1.. as the keys.

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 ToLua and ToLuaMulti 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(())
});

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.

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.

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 futures_timer::Delay;
use mlua::{Lua, Result};

async fn sleep(_lua: &Lua, n: u64) -> Result<&'static str> {
    Delay::new(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(())
}

Wraps a Lua function into a new thread (or coroutine).

Equivalent to coroutine.create.

Create a Lua userdata object from a custom userdata type.

All userdata instances of type T shares the same metatable.

Create a Lua userdata object from a custom serializable userdata type.

Requires feature = "serialize"

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()?;

Returns a handle to the global environment.

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.

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.

An asynchronous version of scope that allows to create scoped async functions and execute them.

Requires feature = "async"

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.

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.

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.

Converts a value that implements ToLua into a Value instance.

Converts a Value instance into a value that implements FromLua.

Converts a value that implements ToLuaMulti into a MultiValue instance.

Converts a MultiValue instance into a value that implements FromLuaMulti.

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.

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.

Removes a named value in the Lua registry.

Equivalent to calling set_named_registry_value with a value of Nil.

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.

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.

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 RegistryKeys have been dropped.

Replaces a value in the Lua registry by its RegistryKey.

See create_registry_value for more details.

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.

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.

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.

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(())
}

Gets a reference to an application data object stored by Lua::set_app_data() of type T.

Gets a mutable reference to an application data object stored by Lua::set_app_data() of type T.

Removes an application data of type T.

Trait Implementations

Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
A special value (lightuserdata) to encode/decode optional (none) values. Read more
A metatable attachable to a Lua table to systematically encode it as Array (instead of Map). As result, encoded Array will contain only sequence part of the table, with the same length as the # operator on that table. Read more
Converts T into a Value instance. Read more
Converts T into a Value instance with options. Read more
Deserializes a Value into any serde deserializable object. Read more
Deserializes a Value into any serde deserializable object with options. Read more

Requires feature = "send"

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.