Skip to main content

Lua

Struct Lua 

Source
pub struct Lua { /* private fields */ }
Expand description

A handle to a Lua interpreter.

Mirrors mlua::Lua. Cloning produces another handle to the same VM (the inner state is shared via Rc), exactly like mlua.

Implementations§

Source§

impl Lua

Source

pub fn set_app_data<T: 'static>(&self, data: T)

Insert (or replace) a value of type T in this VM’s application-data store. Mirrors mlua::Lua::set_app_data.

§Panics

Panics if any app-data value is currently borrowed.

Source

pub fn try_set_app_data<T: 'static>(&self, data: T) -> Result<Option<T>>

Try to insert (or replace) a value of type T. Returns the previous value, or an error if any app-data value is currently borrowed. Mirrors mlua::Lua::try_set_app_data.

Source

pub fn app_data_ref<T: 'static>(&self) -> Option<AppDataRef<T>>

Borrow the application-data value of type T immutably, if present. Mirrors mlua::Lua::app_data_ref.

§Panics

Panics if the value is currently mutably borrowed.

Source

pub fn try_app_data_ref<T: 'static>(&self) -> Result<Option<AppDataRef<T>>>

Try to borrow the application-data value of type T immutably. Returns Ok(None) if absent, Err if it is currently mutably borrowed. Mirrors mlua::Lua::try_app_data_ref.

Source

pub fn app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<T>>

Borrow the application-data value of type T mutably, if present. Mirrors mlua::Lua::app_data_mut.

§Panics

Panics if the value is currently borrowed (immutably or mutably).

Source

pub fn try_app_data_mut<T: 'static>(&self) -> Result<Option<AppDataRefMut<T>>>

Try to borrow the application-data value of type T mutably. Returns Ok(None) if absent, Err if it is currently borrowed. Mirrors mlua::Lua::try_app_data_mut.

Source

pub fn remove_app_data<T: 'static>(&self) -> Option<T>

Remove and return the application-data value of type T, if present. Mirrors mlua::Lua::remove_app_data.

§Panics

Panics if any app-data value is currently borrowed.

Source§

impl Lua

Source

pub fn inspect_stack(&self, level: usize) -> Option<Debug>

Inspect the activation record level frames up the call stack (0 = the currently running function). Returns None if there is no function at that level. Mirrors the Luau-feasible part of mlua::Lua::inspect_stack.

Source§

impl Lua

Source

pub unsafe fn exec_raw<R, F>(&self, args: impl IntoLuaMulti, f: F) -> Result<R>

Run a closure that manipulates the raw luaur stack, under a protected call. Mirrors mlua::Lua::exec_raw.

args are pushed first (as the function arguments); then f runs with the raw *mut lua_State, pushing any results it wants returned. A lua_error raised inside f is caught and returned as an [Error].

§Safety

f operates on the raw stack with no safety net beyond the protected call; it must leave the stack in a consistent state (push results, not underflow). This mirrors mlua::Lua::exec_raw’s unsafe contract.

Source

pub unsafe fn create_c_function(&self, func: lua_CFunction) -> Result<Function>

Wrap a raw luaur lua_CFunction as a Function. Mirrors mlua::Lua::create_c_function.

DEVIATION: luaur’s lua_CFunction is a plain Rust Option<unsafe fn(*mut lua_State) -> c_int> (luaur is a pure-Rust VM with no C ABI boundary), not an extern "C-unwind" fn as in mlua’s FFI build. The function value is otherwise identical; callers pass a luaur-shaped unsafe fn (see ffi::lua_CFunction).

§Safety

The supplied function runs with raw access to the lua_State; it must honor the luaur calling convention (consume its arguments, push its results, return the result count). Mirrors mlua’s unsafe contract.

Source§

impl Lua

Source

pub fn used_memory(&self) -> usize

The number of bytes currently used by the VM. Mirrors mlua::Lua::used_memory (luaur’s totalbytes).

Source

pub fn gc_is_running(&self) -> bool

Whether the GC is currently running. Mirrors mlua::Lua::gc_is_running.

Source

pub fn gc_stop(&self)

Stop the GC. Mirrors mlua::Lua::gc_stop.

Source

pub fn gc_restart(&self)

Restart the GC. Mirrors mlua::Lua::gc_restart.

Source

pub fn gc_count(&self) -> usize

The total memory in use, in KB (the LUA_GCCOUNT op). Mirrors mlua::Lua::gc_count.

Source

pub fn gc_step_kbytes(&self, kbytes: c_int) -> Result<bool>

Run one incremental GC step over kbytes of work. Returns whether a full collection cycle finished. Mirrors mlua::Lua::gc_step_kbytes/gc_step.

Source

pub fn gc_step(&self) -> Result<bool>

Run a default-size incremental GC step. Mirrors mlua::Lua::gc_step.

Source

pub fn gc_inc( &self, pause: c_int, step_multiplier: c_int, step_size: c_int, ) -> GcMode

Apply incremental-GC parameters (goal / step multiplier / step size). Mirrors mlua::Lua::gc_inc; returns the previous GcMode (always incremental on Luau).

Source

pub fn gc_set_mode(&self, mode: GcMode) -> GcMode

Set the GC mode, returning the previous mode. Mirrors mlua::Lua::gc_set_mode.

DEVIATION: Luau is always incremental. Passing GcMode::Incremental applies its params and returns the prior (incremental) mode; passing GcMode::Generational is a no-op that returns the current incremental mode.

Source§

impl Lua

Source

pub fn set_interrupt<F>(&self, callback: F)
where F: Fn(&Lua) -> Result<VmState> + MaybeSend + 'static,

Install an interrupt callback. Mirrors mlua::Lua::set_interrupt.

The callback runs at VM safepoints; returning VmState::Yield yields the running coroutine, and returning Err raises a Lua error.

Source

pub fn remove_interrupt(&self)

Remove a previously installed interrupt callback. Mirrors mlua::Lua::remove_interrupt.

Source§

impl Lua

Source

pub fn sandbox(&self, enabled: bool) -> Result<()>

Enable or disable sandbox mode. Mirrors mlua::Lua::sandbox.

Enabling sets every library table (and the globals table) read-only and activates safeenv, then installs a fresh proxy global table (via luaL_sandboxthread) so that script-level global writes go to a throwaway table whose __index is the original environment. Disabling restores the original globals table and clears the read-only/safeenv flags.

DEVIATION: Luau’s standard library (as bundled in luaur) does not register collectgarbage; mlua’s sandbox test additionally checks that collectgarbage is restricted under the sandbox. That part is not exercisable here (see tests/mlua_luau.rs).

Source

pub fn set_safeenv(&self, enabled: bool)

Set or clear the safeenv flag on the globals table. Mirrors mlua::Globals::set_safeenv applied to the main globals.

safeenv lets the VM fast-path global reads; clearing it forces the slow path (needed when globals/__index may change at runtime).

Source

pub fn set_compiler(&self, compiler: Compiler)

Install a default Compiler used to compile every chunk loaded by this VM (unless a chunk overrides it via Chunk::set_compiler). Mirrors mlua::Lua::set_compiler.

Source

pub fn set_type_metatable<T: TypeMetatable>(&self, metatable: Option<Table>)

Set (or clear) the metatable shared by all values of a Luau built-in type T. Mirrors mlua::Lua::set_type_metatable.

Implemented for Vector, bool, Number, LuaString, Function, Thread, and LightUserData. Setting it installs a metatable in the VM’s global per-type metatable slot, so e.g. v.x/v:method dispatch through it.

Source

pub fn type_metatable<T: TypeMetatable>(&self) -> Option<Table>

The metatable shared by all values of a Luau built-in type T, if one has been installed. Mirrors mlua::Lua::type_metatable.

Source

pub fn set_fflag(name: &str, _enabled: bool) -> Result<()>

Set a Luau fast-flag (FFlag) by name. Mirrors mlua::Lua::set_fflag.

DEVIATION: luaur’s FastFlags are a fixed, compile-time FFlag enum rather than a string-keyed registry, so there is no way to look a flag up by an arbitrary name. This therefore always reports the name as unknown (Err) — which matches mlua’s contract for an unrecognized flag (the only behavior its test_fflags asserts). Known flags are configured at VM-construction time via luaur_common::set_all_flags.

Source§

impl Lua

Source

pub fn set_memory_limit(&self, limit: usize) -> Result<usize>

Set the VM’s memory limit in bytes (0 = unlimited). Mirrors mlua::Lua::set_memory_limit.

Once installed, an allocation that would exceed the cap fails with Error::MemoryError, both during execution and during chunk loading.

Source

pub fn set_memory_category(&self, name: &str) -> Result<()>

Set the active memory category by name. Mirrors mlua::Lua::set_memory_category.

Category names must be non-empty and consist only of [A-Za-z0-9_]. At most 255 distinct user categories can be created (id 0 is reserved for the implicit "main" category); creating a 256th fails.

Source

pub fn memory_category_bytes(&self, name: &str) -> Option<usize>

The number of bytes accounted to the named memory category, or None if the category was never set on this VM. A luaur-rt extension (mlua tracks this only via heap_dump, which luaur cannot back — see the module).

Source§

impl Lua

Source

pub fn register_module(&self, name: &str, module: impl IntoLua) -> Result<()>

Register module under the alias name so require(name) returns it. Mirrors mlua::Lua::register_module.

As in Luau, a registered module alias must begin with '@'; a name without the prefix is rejected with a runtime error. Lookups are case-insensitive on the alias (matching Luau’s registered-alias rules).

Source

pub fn unload_module(&self, name: &str) -> Result<()>

Remove a previously registered module alias. Mirrors mlua::Lua::unload_module.

Source§

impl Lua

Source

pub fn create_registry_value(&self, value: impl IntoLua) -> Result<RegistryKey>

Store a value in the registry and return a RegistryKey that keeps it alive. Mirrors mlua::Lua::create_registry_value.

Source

pub fn registry_value<T: FromLua>(&self, key: &RegistryKey) -> Result<T>

Read back a value previously stored with Lua::create_registry_value, converting it to T. Mirrors mlua::Lua::registry_value.

Source

pub fn remove_registry_value(&self, key: RegistryKey) -> Result<()>

Remove a value from the registry, releasing its slot. Mirrors mlua::Lua::remove_registry_value.

Source

pub fn replace_registry_value( &self, key: &mut RegistryKey, value: impl IntoLua, ) -> Result<()>

Replace the value stored under an existing key. Mirrors mlua::Lua::replace_registry_value.

Source

pub fn owns_registry_value(&self, key: &RegistryKey) -> bool

Whether this Lua instance owns key (i.e. key was minted by this VM, not a different one). Mirrors mlua::Lua::owns_registry_value.

Source

pub fn expire_registry_values(&self)

Expire any RegistryKeys whose strong handles have all been dropped.

Mirrors mlua::Lua::expire_registry_values. luaur-rt releases a registry slot eagerly when the last clone of its RegistryKey is dropped (via [crate::state::LuaRef]’s Drop calling lua_unref), so there is no deferred-expiry queue to drain; this is a no-op kept for parity.

Source

pub fn set_named_registry_value( &self, name: &str, value: impl IntoLua, ) -> Result<()>

Store a value in the registry under the string name. Mirrors mlua::Lua::set_named_registry_value.

Source

pub fn named_registry_value<T: FromLua>(&self, name: &str) -> Result<T>

Read back a value previously stored with Lua::set_named_registry_value, converting it to T. A name that was never set (or was unset) reads back as nil. Mirrors mlua::Lua::named_registry_value.

Source

pub fn unset_named_registry_value(&self, name: &str) -> Result<()>

Remove a value stored under the string name. Mirrors mlua::Lua::unset_named_registry_value.

Source§

impl Lua

Source

pub fn scope<'env, R>( &self, f: impl for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> Result<R>, ) -> Result<R>

Create a Scope in which non-'static callbacks and userdata can be created, borrowing data from the enclosing stack frame.

Mirrors mlua::Lua::scope. Everything the scope creates is invalidated when this method returns (on every exit path), so the borrows it held are guaranteed to end before the borrowed data can. See Scope and the scope module docs for the soundness argument.

use luaur_rt::prelude::*;
use std::cell::Cell;

let lua = Lua::new();
let counter = Cell::new(0);
lua.scope(|scope| {
    let f = scope.create_function(|_, ()| {
        counter.set(counter.get() + 1);
        Ok(())
    })?;
    f.call::<()>(())?;
    Ok(())
})
.unwrap();
assert_eq!(counter.get(), 1);
Source§

impl Lua

Source

pub fn new() -> Lua

Create a new Lua state with the standard library opened.

Mirrors mlua::Lua::new.

Source

pub fn new_empty() -> Lua

Create a new Lua state without opening the standard library.

A deliberate deviation from mlua (which exposes StdLib flags); a minimal convenience for embedders who want a clean global table.

Source

pub unsafe fn unsafe_new() -> Lua

Create a new Lua state with the standard library opened, without the extra safety restrictions a safe Lua::new would impose.

Mirrors mlua::Lua::unsafe_new. In Luau there is no separate set of “unsafe” base libraries (the debug/ffi/package distinction is a Lua-5.x concept), so this is equivalent to Lua::new; it exists for mlua signature parity.

§Safety

Provided for parity with mlua’s unsafe_new, which can open libraries that allow loading native code. luaur’s Luau base library does not expose such facilities, so this is in practice as safe as Lua::new; the unsafe marker is retained to match mlua’s signature.

Source

pub fn new_with(libs: StdLib, options: LuaOptions) -> Result<Lua>

Create a new Lua state opening the libraries selected by libs, with the behavioral options. Mirrors mlua::Lua::new_with.

DEVIATION: luaur opens the Luau base libraries as a unit, so any non-empty libs opens the full standard library and [StdLib::NONE] opens nothing (see [StdLib]). options is recorded on the VM (currently only catch_rust_panics is observable).

Source§

impl Lua

Source

pub fn weak(&self) -> WeakLua

A non-owning, weak handle to this VM. Mirrors mlua::Lua::weak.

The WeakLua does not keep the VM alive; it can be upgraded back to a strong Lua only while at least one strong handle still exists.

Source§

impl Lua

Source

pub fn globals(&self) -> Table

The globals table.

Mirrors mlua::Lua::globals. Returns a Table handle to the global environment (the table reachable at LUA_GLOBALSINDEX).

Source

pub fn create_table(&self) -> Table

Create a new, empty table.

Mirrors mlua::Lua::create_table (infallible here, so no Result wrapper is strictly needed — but we also provide the _result variant for signature parity below).

Source

pub fn create_table_result(&self) -> Result<Table>

Result-returning alias of Lua::create_table for mlua signature parity.

Source

pub fn create_string(&self, s: impl AsRef<[u8]>) -> LuaString

Create a Lua string from bytes/str.

Mirrors mlua::Lua::create_string.

Source

pub fn create_table_from<K, V, I>(&self, iter: I) -> Result<Table>
where K: IntoLua, V: IntoLua, I: IntoIterator<Item = (K, V)>,

Create a table and populate it from an iterator of key/value pairs.

Mirrors mlua::Lua::create_table_from.

Source

pub fn create_sequence_from<V, I>(&self, iter: I) -> Result<Table>
where V: IntoLua, I: IntoIterator<Item = V>,

Create a sequence (1-based array) table from an iterator of values.

Mirrors mlua::Lua::create_sequence_from.

Source

pub fn gc_collect(&self) -> Result<()>

Run a full garbage-collection cycle.

Mirrors mlua::Lua::gc_collect (infallible here — luaur’s lua_gc cannot fail for collect).

Source

pub fn create_function<F, A, R>(&self, func: F) -> Result<Function>
where F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static, A: FromLuaMulti, R: IntoLuaMulti,

Create a Lua function from a Rust closure.

Mirrors mlua::Lua::create_function. The closure receives &Lua and the arguments converted via FromLuaMulti; its Ok return is converted via IntoLuaMulti. Returning Err (or panicking) surfaces as a catchable Lua error.

Source

pub fn create_function_mut<F, A, R>(&self, func: F) -> Result<Function>
where F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static, A: FromLuaMulti, R: IntoLuaMulti,

Create a Lua function from a Rust mutable closure.

Mirrors mlua::Lua::create_function_mut. The closure is guarded by a RefCell; a re-entrant call (the callback running Lua that calls the same callback again) surfaces as Error::RecursiveMutCallback rather than allowing mutable aliasing.

Source

pub fn create_userdata<T: UserData + MaybeSend + MaybeSync + 'static>( &self, data: T, ) -> Result<AnyUserData>

Create userdata wrapping a T: UserData value.

Mirrors mlua::Lua::create_userdata.

Source

pub fn create_buffer(&self, data: impl AsRef<[u8]>) -> Result<Buffer>

Creates and returns a Luau buffer object from a byte slice of data.

Mirrors mlua::Lua::create_buffer.

Source

pub fn create_buffer_with_capacity(&self, size: usize) -> Result<Buffer>

Creates and returns a Luau buffer object with the specified size.

Size limit is 1GB. All bytes are initialized to zero. Exceeding the limit returns a RuntimeError carrying a "memory allocation error" message (matching mlua).

Mirrors mlua::Lua::create_buffer_with_capacity.

Source

pub fn create_vector(&self, x: f32, y: f32, z: f32) -> Vector

Creates and returns a Luau Vector value.

Mirrors mlua::Lua::create_vector. luaur is a 3-wide vector build.

Source

pub fn load(&self, source: impl AsRef<str>) -> Chunk

Load a chunk of Lua source for execution.

Mirrors mlua::Lua::load. Returns a Chunk; finalize with Chunk::exec / Chunk::eval / Chunk::into_function.

Source

pub fn pack(&self, value: impl IntoLua) -> Result<Value>

Convert a Rust value into a single Lua Value.

Mirrors mlua::Lua::pack-ish convenience. Provided so callers can build Values without importing the trait.

Source

pub fn pack_multi(&self, values: impl IntoLuaMulti) -> Result<MultiValue>

Build a MultiValue from anything IntoLuaMulti.

Source

pub fn unpack_multi<T: FromLuaMulti>(&self, values: MultiValue) -> Result<T>

Convert any FromLuaMulti from a packed MultiValue. Mirrors mlua::Lua::unpack_multi (and unpack for the single-value case).

Source

pub fn unpack<T: FromLua>(&self, value: Value) -> Result<T>

Convert a single Lua Value to a Rust value. Mirrors mlua::Lua::unpack.

Source

pub fn coerce_integer(&self, value: Value) -> Result<Option<Integer>>

Coerce a Value to an integer the way Lua’s tonumber+integer check would ("1" -> Some(1), "1.5" -> None, a non-numeric value -> None). Mirrors mlua::Lua::coerce_integer.

Source

pub fn coerce_number(&self, value: Value) -> Result<Option<Number>>

Coerce a Value to a float the way Lua’s tonumber would. Mirrors mlua::Lua::coerce_number.

Source

pub fn set_globals(&self, globals: Table) -> Result<()>

Replace the global environment with globals. Mirrors mlua::Lua::set_globals.

In a sandboxed Lua state the globals table is read-only and cannot be replaced; this returns a Error::RuntimeError in that case (matching mlua / Luau).

Source

pub fn traceback(&self, msg: Option<&str>, level: usize) -> Result<LuaString>

Build a stack traceback string for this VM. Mirrors mlua::Lua::traceback.

msg, if present, is prepended to the traceback; level selects the starting stack level. The returned LuaString holds the traceback as produced by luaL_traceback.

Source§

impl Lua

Source

pub fn create_thread(&self, func: Function) -> Result<Thread>

Create a new coroutine from a Function. Mirrors mlua::Lua::create_thread.

Source

pub fn current_thread(&self) -> Thread

The currently-running thread. Mirrors mlua::Lua::current_thread.

Inside a Rust callback this is the coroutine (or main thread) that invoked it. Under the async feature, a coroutine created implicitly by call_async is transparent: this returns its owner thread instead, so current_thread() is stable across the implicit-coroutine boundary (matching mlua).

Trait Implementations§

Source§

impl Clone for Lua

Source§

fn clone(&self) -> Lua

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Default for Lua

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !Send for Lua

§

impl !Sync for Lua

§

impl Freeze for Lua

§

impl RefUnwindSafe for Lua

§

impl Unpin for Lua

§

impl UnsafeUnpin for Lua

§

impl UnwindSafe for Lua

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> MaybeSend for T

Source§

impl<T> MaybeSync for T

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.