Skip to main content

LuaVM

Struct LuaVM 

Source
pub struct LuaVM {
    pub const_strings: ConstString,
    /* private fields */
}
Expand description

Global VM state (equivalent to global_State in Lua C API) Manages global resources shared by all execution threads/coroutines

Fields§

§const_strings: ConstString

Implementations§

Source§

impl LuaVM

Source

pub fn new(option: SafeOption) -> Box<Self>

Source

pub fn main_state(&mut self) -> &mut LuaState

Source

pub fn main_state_ref(&self) -> &LuaState

Source

pub fn registry_seti(&mut self, key: i64, value: LuaValue)

Set a value in the registry by integer key

Source

pub fn registry_geti(&self, key: i64) -> Option<LuaValue>

Get a value from the registry by integer key

Source

pub fn registry_set(&mut self, key: &str, value: LuaValue) -> LuaResult<()>

Set a value in the registry by string key

Source

pub fn registry_get(&mut self, key: &str) -> LuaResult<Option<LuaValue>>

Get a value from the registry by string key

Source

pub fn create_ref(&mut self, value: LuaValue) -> LuaRefValue

Create a reference to a Lua value (like luaL_ref in C API)

This stores the value in the registry and returns a LuaRefValue.

  • For nil: returns LUA_REFNIL (no storage)
  • For GC objects: stores in registry, returns ref ID
  • For simple values: stores directly in LuaRefValue

You must call release_ref() when done to free registry entries.

Source

pub fn get_ref_value(&self, lua_ref: &LuaRefValue) -> LuaValue

Get the value from a reference

Source

pub fn release_ref(&mut self, lua_ref: LuaRefValue)

Release a reference created by create_ref (like luaL_unref in C API)

This frees the registry entry and allows the value to be garbage collected. After calling this, the LuaRefValue should not be used.

Source

pub fn release_ref_id(&mut self, ref_id: RefId)

Release a reference by raw ID (for C API compatibility)

Source

pub fn get_ref_value_by_id(&self, ref_id: RefId) -> LuaValue

Get value from registry by raw ref ID (for C API compatibility)

Source

pub fn open_stdlib(&mut self, lib: Stdlib) -> LuaResult<()>

Source

pub fn execute(&mut self, chunk: Rc<Chunk>) -> LuaResult<Vec<LuaValue>>

Execute a chunk in the main thread

Source

pub fn execute_string(&mut self, source: &str) -> LuaResult<Vec<LuaValue>>

Source

pub fn compile(&mut self, source: &str) -> LuaResult<Chunk>

Compile source code using VM’s string pool

Source

pub fn compile_with_name( &mut self, source: &str, chunk_name: &str, ) -> LuaResult<Chunk>

Source

pub fn get_global(&mut self, name: &str) -> LuaResult<Option<LuaValue>>

Source

pub fn set_global(&mut self, name: &str, value: LuaValue) -> LuaResult<()>

Source

pub fn set_string_metatable( &mut self, string_lib_table: LuaValue, ) -> LuaResult<()>

Set the metatable for all strings This allows string methods to be called with : syntax (e.g., str:upper())

Source

pub fn create_thread(&mut self, func: LuaValue) -> CreateResult

Create a new thread (coroutine) - returns ThreadId-based LuaValue OPTIMIZED: Minimal initial allocations - grows on demand

Source

pub fn resume_thread( &mut self, thread_val: LuaValue, args: Vec<LuaValue>, ) -> LuaResult<(bool, Vec<LuaValue>)>

Resume a coroutine - DEPRECATED: Use thread_state.resume() instead This method is kept for backward compatibility but delegates to LuaState

Source

pub fn raw_get( &self, table_value: &LuaValue, key: &LuaValue, ) -> Option<LuaValue>

Fast table get - NO metatable support! Use this for normal field access (GETFIELD, GETTABLE, GETI) This is the correct behavior for Lua bytecode instructions Only use table_get_with_meta when you explicitly need __index metamethod

Source

pub fn register_async<F, Fut>(&mut self, name: &str, f: F) -> LuaResult<()>
where F: Fn(Vec<LuaValue>) -> Fut + 'static, Fut: Future<Output = LuaResult<Vec<AsyncReturnValue>>> + 'static,

Register an async function as a Lua global.

The async function factory f receives the Lua arguments as Vec<LuaValue> and returns a Future that produces LuaResult<Vec<LuaValue>>.

From Lua code, the function looks and behaves like a normal synchronous function. The async yield/resume is driven transparently by AsyncThread.

Important: The function MUST be called from within an AsyncThread (i.e., the coroutine must be yieldable). Use create_async_thread() or execute_string_async() to run Lua code that calls async functions.

§Example
vm.register_async("sleep", |args| async move {
    let secs = args[0].as_number().unwrap_or(1.0);
    tokio::time::sleep(Duration::from_secs_f64(secs)).await;
    Ok(vec![LuaValue::boolean(true)])
})?;
Source

pub fn create_async_thread( &mut self, chunk: Chunk, args: Vec<LuaValue>, ) -> LuaResult<AsyncThread>

Create an AsyncThread from a pre-compiled chunk.

The chunk is loaded into a new coroutine, and the returned AsyncThread can be .awaited to drive execution.

§Example
let chunk = vm.compile("return async_fn()")?;
let thread = vm.create_async_thread(chunk, vec![])?;
let results = thread.await?;
Source

pub async fn execute_string_async( &mut self, source: &str, ) -> LuaResult<Vec<LuaValue>>

Compile and execute Lua source code asynchronously.

This is the simplest way to run Lua code that may call async functions. Internally creates a coroutine and drives it with AsyncThread.

§Example
vm.register_async("fetch", |args| async move { ... })?;
let results = vm.execute_string_async("return fetch('https://...')").await?;
Source

pub fn register_enum<T: LuaEnum>(&mut self, name: &str) -> LuaResult<()>

Register a Rust enum as a Lua global table of integer constants.

Each variant becomes a key in the table with its discriminant as value. The enum must implement LuaEnum (auto-derived by #[derive(LuaUserData)] on C-like enums).

§Example
#[derive(LuaUserData)]
enum Color { Red, Green, Blue }

vm.register_enum::<Color>("Color")?;
// Lua: Color.Red == 0, Color.Green == 1, Color.Blue == 2
Source

pub fn raw_set( &mut self, table_value: &LuaValue, key: LuaValue, value: LuaValue, ) -> bool

Source

pub fn raw_geti(&self, table_value: &LuaValue, key: i64) -> Option<LuaValue>

Source

pub fn raw_seti( &mut self, table_value: &LuaValue, key: i64, value: LuaValue, ) -> bool

Source

pub fn create_string(&mut self, s: &str) -> CreateResult

Create a string and register it with GC For short strings (4 bytes), use interning (global deduplication) Create a string value with automatic interning for short strings Returns LuaValue directly with ZERO allocation overhead for interned strings

Performance characteristics:

  • Cache hit (interned): O(1) hash lookup, 0 allocations, 0 atomic ops
  • Cache miss (new): 1 Box allocation, GC registration, pool insertion
  • Long string: 1 Box allocation, GC registration, no pooling
Source

pub fn create_binary(&mut self, data: Vec<u8>) -> CreateResult

Source

pub fn create_string_owned(&mut self, s: String) -> CreateResult

Create string from owned String (avoids clone for non-interned strings)

Source

pub fn create_substring( &mut self, s_value: LuaValue, start: usize, end: usize, ) -> CreateResult

Create substring (optimized for string.sub)

Source

pub fn create_table( &mut self, array_size: usize, hash_size: usize, ) -> CreateResult

Create a new table

Source

pub fn create_userdata(&mut self, data: LuaUserdata) -> CreateResult

Create new userdata

Source

pub fn create_function( &mut self, chunk: Rc<Chunk>, upvalues: UpvalueStore, ) -> CreateResult

Create a function in object pool

Source

pub fn create_c_closure( &mut self, func: CFunction, upvalues: Vec<LuaValue>, ) -> CreateResult

Create a C closure (native function with upvalues stored as closed upvalues) The upvalues are automatically created as closed upvalues with the given values

Source

pub fn create_rclosure( &mut self, func: RustCallback, upvalues: Vec<LuaValue>, ) -> CreateResult

Create an RClosure from a Rust closure (Box). Unlike CFunction (bare fn pointer), this can capture arbitrary Rust state.

Source

pub fn create_closure<F>(&mut self, func: F) -> CreateResult
where F: Fn(&mut LuaState) -> LuaResult<usize> + 'static,

Convenience: create an RClosure from any Fn(&mut LuaState) -> LuaResult<usize> + 'static. Boxes the closure automatically.

Source

pub fn create_closure_with_upvalues<F>( &mut self, func: F, upvalues: Vec<LuaValue>, ) -> CreateResult
where F: Fn(&mut LuaState) -> LuaResult<usize> + 'static,

Convenience: create an RClosure with upvalues from any Fn(&mut LuaState) -> LuaResult<usize> + 'static.

Source

pub fn create_upvalue_open( &mut self, stack_index: usize, ptr: LuaValuePtr, ) -> LuaResult<UpvaluePtr>

Create an open upvalue pointing to a stack index

Source

pub fn create_upvalue_closed( &mut self, value: LuaValue, ) -> LuaResult<UpvaluePtr>

Create a closed upvalue with a value

Source

pub fn gc_stats(&self) -> String

Get GC statistics

Source

pub fn error(&mut self, message: impl Into<String>) -> LuaError

Source

pub fn compile_error(&mut self, message: impl Into<String>) -> LuaError

Source

pub fn get_error_message(&mut self, e: LuaError) -> String

Source

pub fn generate_traceback(&mut self, error_msg: &str) -> String

Generate a stack traceback string

Source

pub fn protected_call( &mut self, func: LuaValue, args: Vec<LuaValue>, ) -> LuaResult<(bool, Vec<LuaValue>)>

Execute a function with protected call (pcall semantics) Note: Yields are NOT caught by pcall - they propagate through

Source

pub fn protected_call_stack_based( &mut self, func_idx: usize, arg_count: usize, ) -> LuaResult<(bool, usize)>

ULTRA-OPTIMIZED pcall for CFunction calls Works directly on the stack without any Vec allocations Returns: (success, result_count) where results are on stack

Source

pub fn protected_call_with_handler( &mut self, func: LuaValue, args: Vec<LuaValue>, err_handler: LuaValue, ) -> LuaResult<(bool, Vec<LuaValue>)>

Protected call with error handler (xpcall semantics) The error handler is called if an error occurs Note: Yields are NOT caught by xpcall - they propagate through

Source

pub fn get_main_thread_ptr(&self) -> ThreadPtr

Source

pub fn get_basic_metatable(&self, kind: LuaValueKind) -> Option<LuaValue>

Source

pub fn set_basic_metatable(&mut self, kind: LuaValueKind, mt: Option<LuaValue>)

Source

pub fn get_basic_metatables(&self) -> Vec<LuaValue>

Auto Trait Implementations§

§

impl Freeze for LuaVM

§

impl !RefUnwindSafe for LuaVM

§

impl !Send for LuaVM

§

impl !Sync for LuaVM

§

impl Unpin for LuaVM

§

impl UnsafeUnpin for LuaVM

§

impl !UnwindSafe for LuaVM

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> 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> LuaMethodProvider for T

Source§

impl<T> LuaStaticMethodProvider for T

Source§

fn __lua_static_methods() -> &'static [(&'static str, CFunction)]

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.