pub struct Lua<const ID_SIZE: usize = DEFAULT_ID_SIZE> { /* private fields */ }Expand description
Implementations§
source§impl Lua<DEFAULT_ID_SIZE>
impl Lua<DEFAULT_ID_SIZE>
pub fn new_auxlib_default() -> Option<Self>
sourcepub fn new_default() -> Option<Self>
pub fn new_default() -> Option<Self>
Examples found in repository?
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
fn main() -> ExitCode {
let Some(mut lua) = Lua::new_default() else {
eprintln!("cannot create state: not enough memory");
return ExitCode::FAILURE
};
lua.push_c_function(l_main);
let status = lua.run_managed(|mut mg| mg.pcall(0, 1, 0));
let is_ok = lua.to_boolean(-1);
report(&mut lua, status);
if status.is_ok() && is_ok {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}Methods from Deref<Target = Thread<ID_SIZE>>§
sourcepub fn as_ptr(&self) -> *mut State
pub fn as_ptr(&self) -> *mut State
Return the raw C pointer that represents the underlying Lua state.
sourcepub fn run_managed<R>(&mut self, func: impl FnOnce(Managed<'_>) -> R) -> R
pub fn run_managed<R>(&mut self, func: impl FnOnce(Managed<'_>) -> R) -> R
Run code that can restart the GC and potentially invalidate pointers in a context.
Examples found in repository?
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
fn report(lua: &mut LuaThread, status: LuaStatus) -> bool {
if !status.is_ok() {
if let Some(message) = unsafe { lua.to_string(-1) } {
c_eprintln(message);
}
lua.run_managed(|mut mg| unsafe { mg.pop(1) });
false
} else {
true
}
}
unsafe extern "C" fn l_err_handler(l: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(l);
if let Some(msg) = lua.to_string(1) {
lua.traceback(&lua, Some(msg), 1);
return 1
}
let ok = lua.run_managed(|mut mg| {
mg.call_metamethod(1, cstr!("__tostring"))
});
if ok && lua.type_of(-1) == LuaType::String {
return 1
}
lua_push_fmt_string!(lua, "(error object is a %s value)", lua.type_name_of(1));
1
}
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}
fn main() -> ExitCode {
let Some(mut lua) = Lua::new_default() else {
eprintln!("cannot create state: not enough memory");
return ExitCode::FAILURE
};
lua.push_c_function(l_main);
let status = lua.run_managed(|mut mg| mg.pcall(0, 1, 0));
let is_ok = lua.to_boolean(-1);
report(&mut lua, status);
if status.is_ok() && is_ok {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}sourcepub fn run_managed_no_gc<R>(&self, func: impl FnOnce(Managed<'_>) -> R) -> R
pub fn run_managed_no_gc<R>(&self, func: impl FnOnce(Managed<'_>) -> R) -> R
This is the same as Thread::run_managed, however it doesn’t borrow
mutably by assuming that the garbage collector will not collect (and
thus invalidate) any outside references.
§Safety
The body of func must not include any operations that may cause the
garbage collector to run a cycle.
For example, if performing arithmetic on numbers does not trigger any metamethods, or it triggers metamethods that can’t ever cause the collector to collect, then this invariant is not broken.
sourcepub unsafe fn close_as_main(&mut self)
pub unsafe fn close_as_main(&mut self)
Close all active to-be-closed variables in the main thread, release all
objects (calling the corresponding garbage-collection metamethods, if
any), and free all dynamic memory used by this Thread.
pub fn close_as_coroutine(&mut self) -> Status
sourcepub fn at_panic(&self, func: Option<CFunction>) -> Option<CFunction>
pub fn at_panic(&self, func: Option<CFunction>) -> Option<CFunction>
Set a new panic function and return the old one.
sourcepub fn error(&self) -> !
pub fn error(&self) -> !
Raise a Lua error, using the value on the top of the stack as the error object.
This function does a long jump, and therefore never returns.
sourcepub fn mem_kbytes(&self) -> c_uint
pub fn mem_kbytes(&self) -> c_uint
Return the current amount of memory (in kilobytes) in use by this
Thread.
sourcepub fn mem_byte_remainder(&self) -> c_uint
pub fn mem_byte_remainder(&self) -> c_uint
Return the remainder of dividing the current amount of bytes of memory
in use by this Thread by 1024.
sourcepub fn is_gc_running(&self) -> bool
pub fn is_gc_running(&self) -> bool
Return true if the collector is running (i.e. not stopped).
sourcepub fn switch_gc_to(&mut self, gc: GcMode)
pub fn switch_gc_to(&mut self, gc: GcMode)
Change the collector to either incremental or generational mode (see
also GcMode) with the given parameters.
sourcepub fn abs_index(&self, idx: c_int) -> c_int
pub fn abs_index(&self, idx: c_int) -> c_int
Convert the acceptable index idx into an equivalent absolute index
(that is, one that does not depend on the stack size).
sourcepub fn test_stack(&self, n: c_uint) -> bool
pub fn test_stack(&self, n: c_uint) -> bool
Ensure that the stack has space for at least n extra elements.
That is, that you can safely push up to n values into it.
Returns false if it cannot fulfill the request, either because it
would cause the stack to be greater than a fixed maximum size (typically
at least several thousand elements) or because it cannot allocate memory
for the extra space.
This function never shrinks the stack; if the stack already has space for the extra elements, it is left unchanged.
sourcepub fn copy(&self, from_idx: c_int, to_idx: c_int)
pub fn copy(&self, from_idx: c_int, to_idx: c_int)
Copy the element at from_idx into the valid index to_idx, replacing
the value at that position.
Values at other positions are not affected.
sourcepub unsafe fn create_table(&self, n_arr: c_uint, n_rec: c_uint)
pub unsafe fn create_table(&self, n_arr: c_uint, n_rec: c_uint)
Create a new empty table and push it onto the stack.
narr is a hint for how many elements the table will have as a sequence,
and 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.
This preallocation may help performance when its known in advance how
many elements the table will have.
See also Thread::new_table.
§Safety
The underlying Lua state may raise a memory error.
sourcepub fn dump(
&self,
writer: Writer,
writer_data: *mut c_void,
strip_debug_info: bool
) -> Status
pub fn dump( &self, writer: Writer, writer_data: *mut c_void, strip_debug_info: bool ) -> Status
Dump a function as a binary chunk.
This function receives a Lua function on the top of the stack and produces a binary chunk that, if loaded again, results in a function equivalent to the one dumped.
As it produces parts of the chunk, the function calls writer (see also
Writer) with the given data to write them.
If strip_debug_info is true, the binary representation may not
include all debug information about the function, to save space.
The value returned is the error code returned by the last call to the writer.
This function does not pop the Lua function from the stack.
sourcepub fn get_alloc_fn(&self) -> (Alloc, *mut c_void)
pub fn get_alloc_fn(&self) -> (Alloc, *mut c_void)
Return the memory-allocation function of this Thread along with the
opaque pointer given when the memory-allocator function was set.
sourcepub unsafe fn get_global(&self, name: &CStr) -> Type
pub unsafe fn get_global(&self, name: &CStr) -> Type
sourcepub fn get_i_uservalue(&self, ud_index: c_int, n: c_ushort) -> Type
pub fn get_i_uservalue(&self, ud_index: c_int, n: c_ushort) -> Type
Push onto the stack the n-th user value associated with the full
userdata at the given index and returns the type of the pushed value.
If the userdata does not have that value, push nil and return
Type::None.
sourcepub fn get_metatable(&self, obj_index: c_int) -> bool
pub fn get_metatable(&self, obj_index: c_int) -> bool
If the value at the given index has a metatable, push that metatable
onto the stack and return true. Otherwise, push nothing and return
false.
sourcepub fn top(&self) -> c_int
pub fn top(&self) -> c_int
Return the index of the top element in the stack.
Because indices start at 1, this result is equal to the number of
elements in the stack; in particular, 0 means an empty stack.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub fn insert(&self, index: c_int)
pub fn insert(&self, index: c_int)
Move the top element into the given valid index, shifting up the elements above that index to open space.
This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
sourcepub fn is_boolean(&self, index: c_int) -> bool
pub fn is_boolean(&self, index: c_int) -> bool
Return true if the value at the given index is a boolean.
sourcepub fn is_c_function(&self, index: c_int) -> bool
pub fn is_c_function(&self, index: c_int) -> bool
Return true if the value at the given index is a C function.
sourcepub fn is_function(&self, index: c_int) -> bool
pub fn is_function(&self, index: c_int) -> bool
Return true if the value at the given index is a function (either
C or Lua).
sourcepub fn is_integer(&self, index: c_int) -> bool
pub fn is_integer(&self, index: c_int) -> bool
Return true if the value at the given index is an integer.
sourcepub fn is_light_userdata(&self, index: c_int) -> bool
pub fn is_light_userdata(&self, index: c_int) -> bool
Return true if the value at the given index is a light userdata.
sourcepub fn is_none(&self, index: c_int) -> bool
pub fn is_none(&self, index: c_int) -> bool
Return true if the value at the given index is not valid.
sourcepub fn is_none_or_nil(&self, index: c_int) -> bool
pub fn is_none_or_nil(&self, index: c_int) -> bool
Return true if the value at the given index is not valid or is
nil.
sourcepub fn is_number(&self, index: c_int) -> bool
pub fn is_number(&self, index: c_int) -> bool
Return true if the value at the given index is a number.
sourcepub fn is_string(&self, index: c_int) -> bool
pub fn is_string(&self, index: c_int) -> bool
Return true if the value at the given index is a string or a
number, which is always convertible to a string.
sourcepub fn is_table(&self, index: c_int) -> bool
pub fn is_table(&self, index: c_int) -> bool
Return true if the value at the given index is a table.
sourcepub fn is_thread(&self, index: c_int) -> bool
pub fn is_thread(&self, index: c_int) -> bool
Return true if the value at the given index is a thread.
sourcepub fn is_userdata(&self, index: c_int) -> bool
pub fn is_userdata(&self, index: c_int) -> bool
Return true if the value at the given index is a userdata (either
full or light).
sourcepub fn load(
&self,
reader: Reader,
data: *mut c_void,
chunk_name: &CStr,
mode: Option<&CStr>
) -> Status
pub fn load( &self, reader: Reader, data: *mut c_void, chunk_name: &CStr, mode: Option<&CStr> ) -> Status
Load a Lua chunk without running it. If there are no errors, push the compiled chunk as a Lua function. Otherwise, push an error message.
This function uses a user-supplied reader to read the chunk (see also Reader).
data is an opaque value passed to the reader function.
chunk_name gives a name to the chunk, which is used for error messages
and in debug information.
The function automatically detects whether the chunk is text or binary
and loads it accordingly.
The string mode works similarly as in the Lua base library function
load:
Some("b")loads only binary chunks.Some("t")loads only text chunks.Some("bt")loads both binary and text chunks.Noneis equivalent to the string"bt".
This function uses the stack internally, so reader must always leave
the stack unmodified when returning.
If the resulting function has upvalues, its first upvalue is set to the
value of the global environment stored at index REGISTRY_GLOBALS in
the registry.
When loading main chunks, this upvalue will be the _ENV variable.
Other upvalues are initialized with nil.
sourcepub unsafe fn new_table(&self)
pub unsafe fn new_table(&self)
Create a new empty table and push it onto the stack.
See also Thread::create_table.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn new_thread<'l>(&'l self) -> Coroutine<'l, ID_SIZE>
pub unsafe fn new_thread<'l>(&'l self) -> Coroutine<'l, ID_SIZE>
Create a new thread, push it on the stack, and return a Coroutine
that represents this new thread.
The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack. Threads are subject to garbage collection, like any Lua object.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn new_userdata_uv<'l>(
&'l self,
size: usize,
n_uservalues: c_ushort
) -> &'l mut [u8] ⓘ
pub unsafe fn new_userdata_uv<'l>( &'l self, size: usize, n_uservalues: c_ushort ) -> &'l mut [u8] ⓘ
Create and push on the stack a new full userdata, with n_uservalues
associated Lua values, called user values, and an associated block of
raw memory of size bytes.
The user values can be set and read with the functions
Thread::set_i_uservalue and Thread::get_i_uservalue.
The function returns a mutable slice of the block of memory that was allocated by Lua. Lua ensures that the slice is valid as long as the corresponding userdata is alive. Moreover, if the userdata is marked for finalization, it is valid at least until the call to its finalizer.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn new_copy_t<'l, T: Copy>(
&'l self,
value: T,
n_uservalues: c_ushort
) -> &'l mut T
pub unsafe fn new_copy_t<'l, T: Copy>( &'l self, value: T, n_uservalues: c_ushort ) -> &'l mut T
Similar to Thread::new_userdata_uv, but takes an already existing
value and writes it to the allocated userdata.
This function does not give a finalizer for the userdata, so T must be
Copy.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn next(&self, index: c_int) -> bool
pub unsafe fn next(&self, index: c_int) -> bool
Pop a key from the stack, and push a key–value pair from the table at the given index, the “next” pair after the given key.
This function returns true while there are still elements to go
through. If there are no more elements in the table, then this it
returns false and pushes nothing.
§Note on string conversion functions
While traversing a table, avoid calling Thread::to_chars directly on
a key, unless it is known that the key is actually a string.
Thread::to_chars and other similar functions may change the value at
the given index; this confuses the next call to Thread::next.
§Safety
The underlying Lua state may raise an error if a given
key is neither nil nor present in the table.
sourcepub fn push_boolean(&self, value: bool)
pub fn push_boolean(&self, value: bool)
Push a bool onto the stack.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub unsafe fn push_c_closure(&self, func: CFunction, n_upvalues: u8)
pub unsafe fn push_c_closure(&self, func: CFunction, n_upvalues: u8)
Push a new C closure onto the stack.
This function receives a C function func and pushes onto the stack a
Lua value of type function that, when called, invokes the
corresponding C function.
n_upvalues tells how many upvalues this function will have.
Any function to be callable by Lua must follow the correct protocol to
receive its parameters and return its results (see CFunction).
§C closures
When a C function is created, it is possible to associate some values with it, which are called upvalues. These upvalues are then accessible to the function whenever it is called, where the function is called a C closure. To create a C closure:
- Push the initial values for its upvalues onto the stack. (When there are multiple upvalues, the first value is pushed first.)
- Call this function with the argument
n_upvaluestelling how many upvalues will be associated with the function. The function will also pop these values from the stack.
When n_upvalues == 0, this function creates a “light” C function,
which is just a pointer to the C function. In that case, it never raises
a memory error.
See also Thread::push_c_function.
§Safety
The underlying Lua state may raise a memory error if
n_upvalues > 0.
sourcepub fn push_c_function(&self, func: CFunction)
pub fn push_c_function(&self, func: CFunction)
Push a light C function onto the stack (that is, a C function with no upvalues).
See also Thread::push_c_closure.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}
fn main() -> ExitCode {
let Some(mut lua) = Lua::new_default() else {
eprintln!("cannot create state: not enough memory");
return ExitCode::FAILURE
};
lua.push_c_function(l_main);
let status = lua.run_managed(|mut mg| mg.pcall(0, 1, 0));
let is_ok = lua.to_boolean(-1);
report(&mut lua, status);
if status.is_ok() && is_ok {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}sourcepub fn push_global_table(&self)
pub fn push_global_table(&self)
Push the global environment onto the stack.
sourcepub fn push_integer(&self, value: Integer)
pub fn push_integer(&self, value: Integer)
Push an Integer onto the stack.
sourcepub fn push_light_userdata(&self, ptr: *mut c_void)
pub fn push_light_userdata(&self, ptr: *mut c_void)
Push a light userdata onto the stack.
A light userdata represents a plain pointer. It is a value, like a number: it is not created, it has no individual metatable, and it is not collected (as it was never created).
A light userdata is equal to any light userdata with the same C address.
sourcepub unsafe fn push_chars<'l>(&'l self, data: &[c_char]) -> &'l [c_char]
pub unsafe fn push_chars<'l>(&'l self, data: &[c_char]) -> &'l [c_char]
Push a c_char array, represented by a string, onto the stack.
Lua will make or reuse an internal copy of the given string, so the
memory pointed to by data can be safely freed or reused immediately
after the function returns.
The string can contain any binary data, including embedded zeros.
See also Thread::push_byte_str.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn push_byte_str<'l>(&'l self, data: &[u8]) -> &'l [u8] ⓘ
pub unsafe fn push_byte_str<'l>(&'l self, data: &[u8]) -> &'l [u8] ⓘ
Works the same as Thread::push_chars, however it accepts u8s
instead of c_chars.
§Safety
The underlying Lua state may raise a memory error.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub unsafe fn push_string<'l>(&'l self, data: &CStr) -> &'l CStr
pub unsafe fn push_string<'l>(&'l self, data: &CStr) -> &'l CStr
Push a zero-terminated string onto the stack.
Lua will make or reuse an internal copy of the given string, so the
memory pointed to by data can be freed or reused immediately after the
function returns.
See also Thread::push_chars and Thread::push_byte_str.
§Safety
The underlying Lua state may raise a memory error.
sourcepub fn push_thread(&self) -> bool
pub fn push_thread(&self) -> bool
sourcepub fn push_value(&self, index: c_int)
pub fn push_value(&self, index: c_int)
Push a copy of the element at the given index onto the stack.
sourcepub fn raw_equal(&self, idx_a: c_int, idx_b: c_int) -> bool
pub fn raw_equal(&self, idx_a: c_int, idx_b: c_int) -> bool
Return true if the two values in indices idx_a and idx_b are
primitively equal (that is, equal without calling the __eq metamethod).
This also returns false if any of the indices are not valid.
sourcepub fn raw_get(&self, tbl_index: c_int) -> Type
pub fn raw_get(&self, tbl_index: c_int) -> Type
Without calling metamethods, push t[k], where t is the value at the
given index and k is the value on the top of the stack.
The value at tbl_index must be a table.
sourcepub fn raw_get_i(&self, tbl_index: c_int, i: Integer) -> Type
pub fn raw_get_i(&self, tbl_index: c_int, i: Integer) -> Type
Without calling metamethods, push t[i], where t is the value at the
given index.
The value at tbl_index must be a table.
sourcepub fn raw_get_p(&self, tbl_index: c_int, ptr: *const c_void) -> Type
pub fn raw_get_p(&self, tbl_index: c_int, ptr: *const c_void) -> Type
Without calling metamethods, push t[ptr], where t is the value at
the given index and ptr is the given pointer represented as a light
userdata.
The value at tbl_index must be a table.
sourcepub fn raw_length(&self, index: c_int) -> Unsigned
pub fn raw_length(&self, index: c_int) -> Unsigned
Return the raw “length” of the value at the given index.
For strings, this is the string length;
for tables, this is the result of the length operator (#) with no
metamethods;
for userdata, this is the size of the block of memory allocated for the
userdata.
For other values, this call returns 0.
sourcepub fn remove(&self, index: c_int)
pub fn remove(&self, index: c_int)
Remove the element at the given valid index, shifting down the elements above this index to fill the gap.
This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
sourcepub fn replace(&self, index: c_int)
pub fn replace(&self, index: c_int)
Move the top element into the given valid index without shifting any element (therefore replacing the value at that given index), and then pop that top element.
sourcepub fn resume(&self, from: Option<&Thread>, n_args: c_int) -> (Status, c_int)
pub fn resume(&self, from: Option<&Thread>, n_args: c_int) -> (Status, c_int)
Start or resume this Thread (like a coroutine).
from represents the coroutine that is resuming this one.
If there is no such coroutine, this parameter can be None.
This function returns Status::Yielded if the coroutine yields,
Status::Ok if the coroutine finishes its execution without errors,
or an error code in case of errors.
In case of errors, the error object is on the top of the stack.
§Starting a coroutine
To start a coroutine:
- Push the main function plus any arguments onto the empty stack of the thread.
- Then, call this function, with
n_argsbeing the number of arguments. This call returns when the coroutine suspends or finishes its execution.
When it returns, the number of results is saved and the top of the stack
contains the values passed to Thread::yield_with or returned by the
body function.
§Resuming a coroutine
To resume a coroutine:
- Remove the yielded values from its stack
- Push the values to be passed as results from the yield
- Call this function.
sourcepub fn rotate(&self, index: c_int, n_values: c_int)
pub fn rotate(&self, index: c_int, n_values: c_int)
Rotate the stack elements between the valid index index and the top of
the stack.
The elements are rotated n positions in the direction of the top for a
ositive n, or -n positions in the direction of the bottom for a
negative n.
The absolute value of n must not be greater than the size of the slice
being rotated.
This function cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
sourcepub unsafe fn set_global(&self, key: &CStr)
pub unsafe fn set_global(&self, key: &CStr)
sourcepub fn set_i_uservalue(&self, ud_index: c_int, n: c_ushort) -> bool
pub fn set_i_uservalue(&self, ud_index: c_int, n: c_ushort) -> bool
Pop a value from the stack and set it as the new n-th user value
associated to the full userdata at the given index.
Returns false if the userdata does not have that value.
sourcepub fn set_metatable(&self, obj_index: c_int)
pub fn set_metatable(&self, obj_index: c_int)
Pop a table or nil from the stack and sets that value as the new
metatable for the value at the given index. (nil means no metatable.)
sourcepub fn set_warn_fn(&self, warn: Option<WarnFunction>, warn_data: *mut c_void)
pub fn set_warn_fn(&self, warn: Option<WarnFunction>, warn_data: *mut c_void)
Set the warning function to be used by Lua to emit warnings
(see WarnFunction).
The warn_data parameter sets the custom data passed to the warning
function.
sourcepub fn status(&self) -> Status
pub fn status(&self) -> Status
Return the status of the Lua thread represented by this Thread.
The status can be Status::Ok for a normal thread, an error variant
if the thread finished the execution of a Thread::resume with an
error, or Status::Yielded if the thread is suspended.
Functions can only be called in threads with status Status::Ok.
Threads with status Status::Ok or Status::Yielded can be resumed
(to start a new coroutine or resume an existing one).
sourcepub fn to_boolean(&self, idx: c_int) -> bool
pub fn to_boolean(&self, idx: c_int) -> bool
Convert the Lua value at the given index to a bool.
Like all tests in Lua, this returns true for any Lua value different
from false and nil; otherwise it returns false.
If you want to accept only actual boolean values, use
Thread::is_boolean to test the value’s type first.
Examples found in repository?
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
fn main() -> ExitCode {
let Some(mut lua) = Lua::new_default() else {
eprintln!("cannot create state: not enough memory");
return ExitCode::FAILURE
};
lua.push_c_function(l_main);
let status = lua.run_managed(|mut mg| mg.pcall(0, 1, 0));
let is_ok = lua.to_boolean(-1);
report(&mut lua, status);
if status.is_ok() && is_ok {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}sourcepub fn to_c_function(&self, index: c_int) -> Option<CFunction>
pub fn to_c_function(&self, index: c_int) -> Option<CFunction>
Convert a value at the given index to a C function.
If it is not one, return None.
sourcepub fn to_integer(&self, idx: c_int) -> Integer
pub fn to_integer(&self, idx: c_int) -> Integer
This behaves exactly the same as Thread::to_integer_opt, however the
return value is 0 if an integer isn’t present.
sourcepub fn to_integer_opt(&self, idx: c_int) -> Option<Integer>
pub fn to_integer_opt(&self, idx: c_int) -> Option<Integer>
Convert the Lua value at the given index to the signed integral type
Integer.
The Lua value must be an integer, or a number or string convertible to
an integer. Otherwise, this function returns None.
sourcepub unsafe fn to_chars<'l>(&'l self, index: c_int) -> Option<&'l [c_char]>
pub unsafe fn to_chars<'l>(&'l self, index: c_int) -> Option<&'l [c_char]>
Convert the Lua value at the given index to a slice of c_chars,
representing a Lua string.
The Lua value must be a string or a number; otherwise, the function
returns None.
If the value is a number, then this function also changes the actual value in the stack to a string.
The function returns a slice to data inside the Lua state.
This string always has a zero ('\0') after its last character (as in C),
but can contain other zeros in its body.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn to_byte_str<'l>(&'l self, index: c_int) -> Option<&'l [u8]>
pub unsafe fn to_byte_str<'l>(&'l self, index: c_int) -> Option<&'l [u8]>
Works the same as Thread::to_chars, however it returns a slice of
u8s instead of c_chars.
§Safety
The underlying Lua state may raise a memory error.
sourcepub fn to_number(&self, idx: c_int) -> Number
pub fn to_number(&self, idx: c_int) -> Number
This behaves exactly the same as Thread::to_number_opt, however the
return value is 0.0 if a number isn’t present.
sourcepub fn to_number_opt(&self, idx: c_int) -> Option<Number>
pub fn to_number_opt(&self, idx: c_int) -> Option<Number>
Convert the Lua value at the given index to the floating-point number
type Number.
The Lua value must be a number or string convertible to a number.
Otherwise, this function returns None.
sourcepub fn to_pointer(&self, idx: c_int) -> *const c_void
pub fn to_pointer(&self, idx: c_int) -> *const c_void
Convert the value at the given index to a generic C pointer
(*const c_void).
The value can be a userdata, a table, a thread, a string, or a function; otherwise, this function returns null.
Different objects will give different pointers. There is no way to convert the pointer back to its original value.
Typically this function is used only for hashing and debug information.
sourcepub unsafe fn to_string<'l>(&'l self, index: c_int) -> Option<&'l CStr>
pub unsafe fn to_string<'l>(&'l self, index: c_int) -> Option<&'l CStr>
This behaves exactly like Thread::to_chars, however the return value
is a CStr.
See also Thread::to_byte_str.
§Safety
The underlying Lua state may raise a memory error.
Examples found in repository?
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
fn report(lua: &mut LuaThread, status: LuaStatus) -> bool {
if !status.is_ok() {
if let Some(message) = unsafe { lua.to_string(-1) } {
c_eprintln(message);
}
lua.run_managed(|mut mg| unsafe { mg.pop(1) });
false
} else {
true
}
}
unsafe extern "C" fn l_err_handler(l: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(l);
if let Some(msg) = lua.to_string(1) {
lua.traceback(&lua, Some(msg), 1);
return 1
}
let ok = lua.run_managed(|mut mg| {
mg.call_metamethod(1, cstr!("__tostring"))
});
if ok && lua.type_of(-1) == LuaType::String {
return 1
}
lua_push_fmt_string!(lua, "(error object is a %s value)", lua.type_name_of(1));
1
}sourcepub fn to_thread<'l>(&'l self, index: c_int) -> Option<Coroutine<'l, ID_SIZE>>
pub fn to_thread<'l>(&'l self, index: c_int) -> Option<Coroutine<'l, ID_SIZE>>
Convert the value at the given index to a Lua thread, represented by a
Thread.
The value must be a thread; otherwise, the function returns None.
sourcepub fn to_userdata(&self, idx: c_int) -> *mut c_void
pub fn to_userdata(&self, idx: c_int) -> *mut c_void
If the value at the given index is a light or full userdata, return the address it represents. Otherwise, return null.
sourcepub fn type_of(&self, idx: c_int) -> Type
pub fn type_of(&self, idx: c_int) -> Type
Return the type of the value in the given valid index, or Type::None
for a non-valid but acceptable index.
Examples found in repository?
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
unsafe extern "C" fn l_err_handler(l: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(l);
if let Some(msg) = lua.to_string(1) {
lua.traceback(&lua, Some(msg), 1);
return 1
}
let ok = lua.run_managed(|mut mg| {
mg.call_metamethod(1, cstr!("__tostring"))
});
if ok && lua.type_of(-1) == LuaType::String {
return 1
}
lua_push_fmt_string!(lua, "(error object is a %s value)", lua.type_name_of(1));
1
}sourcepub fn type_name<'a>(&'a self, type_tag: Type) -> &'a CStr
pub fn type_name<'a>(&'a self, type_tag: Type) -> &'a CStr
Return the name of the type encoded by type_tag.
sourcepub fn warning(&self, message: &CStr, to_be_continued: bool)
pub fn warning(&self, message: &CStr, to_be_continued: bool)
Emit a warning with the given message.
A message in a call with to_be_continued == true should be continued
in another call to this function.
sourcepub fn xmove(&self, to: &Thread, n_values: c_uint)
pub fn xmove(&self, to: &Thread, n_values: c_uint)
Exchange values between different threads of the same state.
This function pops n_values values from the stack of this thread, and
pushes them onto the stack of the thread to.
sourcepub unsafe fn yield_with(&self, n_results: c_int) -> !
pub unsafe fn yield_with(&self, n_results: c_int) -> !
This behaves exactly like Thread::yield_k_with, however there is no
continuation.
§Safety
This function should be called only outside of hooks. It is Undefined Behavior if the code after a call to this function is reachable.
sourcepub unsafe fn yield_in_hook_with(&self, n_results: c_int)
pub unsafe fn yield_in_hook_with(&self, n_results: c_int)
This behaves exactly like Thread::yield_in_hook_k_with, however
there is no continuation.
§Safety
This function should be called only outside of hooks. It is Undefined Behavior if the code after a call to this function is reachable.
sourcepub unsafe fn yield_k_with(
&self,
n_results: c_int,
continuation: KFunction,
context: KContext
) -> !
pub unsafe fn yield_k_with( &self, n_results: c_int, continuation: KFunction, context: KContext ) -> !
Yield this thread (like a coroutine).
When this function is called, the running coroutine suspends its
execution, and the call to Thread::resume that started this
coroutine returns.
The parameter n_results is the number of values from the stack that
will be passed as results to Thread::resume.
When the coroutine is resumed again, Lua calls the given continuation
function continuation to continue the execution of the C function that
yielded.
This continuation function receives the same stack from the previous
function, with the n_results results removed and replaced by the
arguments passed to Thread::resume.
Moreover, the continuation function receives the value context that
was originally passed.
Usually, this function does not return; when the coroutine eventually
resumes, it continues executing the continuation function.
However, there is one special case, which is when this function is
called from inside a line or a count hook (see Hook).
In that case, Thread::yield_in_hook_with should be called
(thus, no continuation) and no results, and the hook should return
immediately after the call.
Lua will yield and, when the coroutine resumes again, it will continue
the normal execution of the (Lua) function that triggered the hook.
§Safety
This function should be called only outside of hooks. It is Undefined Behavior if the code after a call to this function is reachable.
The underlying Lua thread can also raise an error if the function is called from a thread with a pending C call with no continuation function (what is called a C-call boundary), or it is called from a thread that is not running inside a resume (typically the main thread).
sourcepub unsafe fn yield_in_hook_k_with(
&self,
n_results: c_int,
continuation: KFunction,
context: KContext
)
pub unsafe fn yield_in_hook_k_with( &self, n_results: c_int, continuation: KFunction, context: KContext )
This behaves exactly like Thread::yield_k_with, however it should
only be called in hooks.
§Safety
This function should be called only inside of hooks.
The underlying Lua thread can also raise an error if the function is called from a thread with a pending C call with no continuation function (what is called a C-call boundary), or it is called from a thread that is not running inside a resume (typically the main thread).
sourcepub fn hook_count(&self) -> c_int
pub fn hook_count(&self) -> c_int
Return the current hook count.
sourcepub fn get_info(&self, what: &CStr, ar: &mut Debug<ID_SIZE>) -> bool
pub fn get_info(&self, what: &CStr, ar: &mut Debug<ID_SIZE>) -> bool
Gets information about a specific function or function invocation.
See also DebugWhat for generating what.
sourcepub fn get_local<'dbg>(
&self,
ar: Option<&'dbg Debug<ID_SIZE>>,
n: c_int
) -> Option<&'dbg CStr>
pub fn get_local<'dbg>( &self, ar: Option<&'dbg Debug<ID_SIZE>>, n: c_int ) -> Option<&'dbg CStr>
Get information about a local variable or a temporary value of a given activation record or function.
The function pushes the variable’s value onto the stack and returns its
name.
It returns None (and pushes nothing) when the index is greater than
the number of active local variables.
§Activation records
For activation records, the parameter ar must be a valid activation
record that was filled by a previous call to Thread::get_stack or
given as argument to a hook (see Hook).
The index n selects which local variable to inspect.
§Functions
For functions, ar must be None and the function to be inspected must
be on the top of the stack.
In this case, only parameters of Lua functions are visible (as there is
no information about what variables are active) and no values are pushed
onto the stack.
sourcepub fn get_stack(&self, level: c_int) -> Option<Debug<ID_SIZE>>
pub fn get_stack(&self, level: c_int) -> Option<Debug<ID_SIZE>>
Get information about the interpreter runtime stack.
This function fills parts of a Debug structure with an
identification of the activation record of 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).
When called with a level greater than the stack depth, this function
returns None.
sourcepub fn get_upvalue<'l>(&'l self, func_index: c_int, n: u8) -> Option<&'l CStr>
pub fn get_upvalue<'l>(&'l self, func_index: c_int, n: u8) -> Option<&'l CStr>
Get information about the n-th upvalue of the closure at index
func_index.
This function pushes the upvalue’s value onto the stack and returns its
name. Returns None (and pushes nothing) when the index n is greater
than the number of upvalues.
sourcepub fn set_hook(&self, hook: Hook<ID_SIZE>, mask: HookMask, count: c_int)
pub fn set_hook(&self, hook: Hook<ID_SIZE>, mask: HookMask, count: c_int)
Set the debugging hook function.
hook is the hook function.
mask specifies on which events the hook will be called: it is formed
by HookMask.
count is only meaningful when the mask includes the count hook
(with HookMask::with_instructions).
For each event, the hook is called as explained below:
- The call hook is called when the interpreter calls a function. The hook is called just after Lua enters the new function.
- The return hook is called when the interpreter returns from a function. The hook is called just before Lua leaves the function.
- The line hook is called when the interpreter is about to start the execution of a new line of code, or when it jumps back in the code (even to the same line). This event only happens while Lua is executing a Lua function.
- The count hook is called after the interpreter executes every
countinstructions. This event only happens while Lua is executing a Lua function.
Hooks are disabled by supplying an empty mask.
sourcepub unsafe fn set_local<'dbg>(
&self,
ar: &'dbg Debug<ID_SIZE>,
n: c_int
) -> Option<&'dbg CStr>
pub unsafe fn set_local<'dbg>( &self, ar: &'dbg Debug<ID_SIZE>, n: c_int ) -> Option<&'dbg CStr>
Set the value of a local variable of a given activation record and return its name.
Returns None (and pops nothing) when the index is greater than the
number of active local variables.
This function assigns the value on the top of the stack to the variable. It also pops the value from the stack.
sourcepub unsafe fn set_upvalue<'l>(&'l self, func_index: c_int, n: u8) -> &'l CStr
pub unsafe fn set_upvalue<'l>(&'l self, func_index: c_int, n: u8) -> &'l CStr
Set the value of a closure’s upvalue and return its name.
Returns None (and pops nothing) when the index n is greater than the
number of upvalues.
This function assigns the value on the top of the stack to the upvalue. It also pops the value from the stack.
sourcepub fn upvalue_id(&self, func_index: c_int, n: u8) -> *mut c_void
pub fn upvalue_id(&self, func_index: c_int, n: u8) -> *mut c_void
Return a unique identifier for the upvalue numbered n from the closure
at index func_index.
These unique identifiers allow a program to check whether different closures share upvalues. Lua closures that share an upvalue (that is, that access a same external local variable) will return identical ids for those upvalue indices.
sourcepub fn upvalue_join(
&self,
func_into_index: i32,
n_into: u8,
func_from_index: i32,
n_from: u8
)
pub fn upvalue_join( &self, func_into_index: i32, n_into: u8, func_from_index: i32, n_from: u8 )
Make the
n_into-th upvalue of the Lua closure at index func_into_index
refer to the
n_from-th upvalue of the Lua closure at index func_from_index.
sourcepub fn new_buffer<'l>(&'l self) -> Buffer<'l>
pub fn new_buffer<'l>(&'l self) -> Buffer<'l>
sourcepub fn arg_error(&self, arg: c_int, extra_message: &CStr) -> !
pub fn arg_error(&self, arg: c_int, extra_message: &CStr) -> !
Raise an error reporting a problem with argument arg of the C function
that called it, using a standard message that includes extra_message
as a comment:
bad argument #<argument> to '<function name>' (<message>)
This function never returns.
sourcepub unsafe fn check_integer(&self, arg: c_int) -> Integer
pub unsafe fn check_integer(&self, arg: c_int) -> Integer
sourcepub unsafe fn check_chars<'l>(&'l self, arg: c_int) -> &'l [c_char]
pub unsafe fn check_chars<'l>(&'l self, arg: c_int) -> &'l [c_char]
sourcepub unsafe fn check_byte_str<'l>(&'l self, arg: c_int) -> &'l [u8] ⓘ
pub unsafe fn check_byte_str<'l>(&'l self, arg: c_int) -> &'l [u8] ⓘ
Works the same as Thread::check_chars, however it returns an array
of u8s instead of c_chars.
§Safety
The underlying Lua state may raise an error if the
argument arg isn’t a string.
sourcepub unsafe fn check_number(&self, arg: c_int) -> Number
pub unsafe fn check_number(&self, arg: c_int) -> Number
sourcepub unsafe fn check_option<const N: usize>(
&self,
arg: c_int,
default: Option<&CStr>,
list: AuxOptions<'_, N>
) -> usize
pub unsafe fn check_option<const N: usize>( &self, arg: c_int, default: Option<&CStr>, list: AuxOptions<'_, N> ) -> usize
Check whether the function argument arg is a string, search for this
string in the option list list and return the index in the list where
the string was found.
If default is Some, the function uses it as a default value when
there is no argument arg or when this argument is nil.
This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)
§Safety
The underlying Lua state may raise an error if the
argument arg is not a string or if the string cannot be found in list.
sourcepub unsafe fn check_stack(&self, size: c_int, message: Option<&CStr>)
pub unsafe fn check_stack(&self, size: c_int, message: Option<&CStr>)
sourcepub unsafe fn check_string<'l>(&'l self, arg: c_int) -> &'l CStr
pub unsafe fn check_string<'l>(&'l self, arg: c_int) -> &'l CStr
sourcepub unsafe fn check_type(&self, arg: c_int, type_tag: Type)
pub unsafe fn check_type(&self, arg: c_int, type_tag: Type)
sourcepub unsafe fn check_udata(&self, arg: c_int, table_name: &CStr) -> NonNull<u8>
pub unsafe fn check_udata(&self, arg: c_int, table_name: &CStr) -> NonNull<u8>
Check whether the function argument arg is a userdata of the type
table_name (see also Thread::new_metatable) and return the
userdata’s memory-block address (see Thread::to_userdata).
§Safety
The underlying Lua state may raise an error if the
argument arg’s type is incorrect.
sourcepub unsafe fn check_version(&self)
pub unsafe fn check_version(&self)
Check whether the code making the call and the Lua library being called are using the same version of Lua and the same numeric types.
§Safety
The underlying Lua state may raise an error if the above requirements aren’t met.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub fn error_str(&self, message: &CStr) -> !
pub fn error_str(&self, message: &CStr) -> !
Raise an error.
This function adds the file name and the line number where the error
occurred at the beginning of message, if this information is available.
This function never returns.
sourcepub unsafe fn exec_result(&self, status: c_int) -> c_int
pub unsafe fn exec_result(&self, status: c_int) -> c_int
sourcepub unsafe fn file_result(&self, status: c_int, file_name: &CStr) -> c_int
pub unsafe fn file_result(&self, status: c_int, file_name: &CStr) -> c_int
sourcepub unsafe fn get_meta_field(&self, obj_index: c_int, event: &CStr) -> Type
pub unsafe fn get_meta_field(&self, obj_index: c_int, event: &CStr) -> Type
Push onto the stack the field event from the metatable of the object
at index obj_index and return the type of the pushed value.
If the object does not have a metatable, or if the metatable does not
have this field, this function pushes nothing and returns Type::Nil.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn get_aux_metatable(&self, table_name: &CStr) -> Type
pub unsafe fn get_aux_metatable(&self, table_name: &CStr) -> Type
Push onto the stack the metatable associated with the name table_name
in the registry (see also Thread::new_metatable), or nil if there
is no metatable associated with that name, and return the type of the
pushed value.
§Safety
The underlying Lua state may raise a memory error.
sourcepub fn load_chars(&self, buffer: &[c_char], name: &CStr) -> Status
pub fn load_chars(&self, buffer: &[c_char], name: &CStr) -> Status
Load a buffer as a Lua chunk. This function uses Thread::load to
load the chunk in the buffer pointed to by buffer.
This function returns the same results as Thread::load.
name is the chunk name, used for debug information and error messages.
sourcepub fn load_byte_str(&self, buffer: &[u8], name: &CStr) -> Status
pub fn load_byte_str(&self, buffer: &[u8], name: &CStr) -> Status
Works the same as Thread::load_chars, however it accepts an array of
u8s instead of c_chars.
sourcepub unsafe fn load_file(&self, file_name: &CStr) -> Status
pub unsafe fn load_file(&self, file_name: &CStr) -> Status
Load a file as a Lua chunk.
This function uses Thread::load to load the chunk in the file
file_name.
The first line in the file is ignored if it starts with a #.
§Safety
The underlying Lua state may raise a memory error.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub unsafe fn load_stdin(&self) -> Status
pub unsafe fn load_stdin(&self) -> Status
Load a Lua chunk from the standard input.
This function uses Thread::load to load the chunk.
The first line in the file is ignored if it starts with a #.
§Safety
The underlying Lua state may raise a memory error.
Examples found in repository?
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
unsafe extern "C" fn l_main(lua: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(lua);
unsafe { lua.check_version() };
lua.run_managed(|mut mg| unsafe { mg.open_libs() });
lua.push_c_function(l_err_handler);
let base = lua.top();
let mut arguments = args().skip(1);
let load_status = if let Some(mut file_name) = arguments.nth(0) {
lua.load_file(unsafe {
file_name.push('\0');
CStr::from_bytes_until_nul(file_name.as_bytes()).unwrap_unchecked()
})
} else {
lua.load_stdin()
};
if !report(&mut lua, load_status) {
return 0
}
let mut arg_count: c_uint = 0;
for arg in arguments {
unsafe { lua.push_byte_str(arg.as_bytes()) };
arg_count += 1;
}
let run_status = lua.run_managed(|mut mg| mg.pcall(arg_count, 0, base));
if !report(&mut lua, run_status) {
return 0
}
lua.push_boolean(true);
1
}sourcepub fn load_string(&self, code: &CStr) -> Status
pub fn load_string(&self, code: &CStr) -> Status
Load a string as a Lua chunk.
This function uses Thread::load to load the chunk in the
zero-terminated string code.
sourcepub unsafe fn new_metatable(&self, table_name: &CStr) -> bool
pub unsafe fn new_metatable(&self, table_name: &CStr) -> bool
If the registry already doesn’t have the key table_name, create a new
table to be used as a metatable for userdata and return true.
Otherwise, return false.
In both cases, the function pushes onto the stack the final value
associated with table_name in the registry.
The function adds to this new table the pair __name = table_name,
adds to the registry the pair [table_name] = table, and returns true.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn opt_integer(&self, arg: c_int, default: Integer) -> Integer
pub unsafe fn opt_integer(&self, arg: c_int, default: Integer) -> Integer
sourcepub unsafe fn opt_chars<'l>(
&'l self,
arg: c_int,
default: &'l CStr
) -> &'l [c_char]
pub unsafe fn opt_chars<'l>( &'l self, arg: c_int, default: &'l CStr ) -> &'l [c_char]
If the function argument arg is a string, return this string, or
return default.
This function uses Thread::to_chars to get its result, so all
conversions and caveats of that function apply here.
§Safety
The underlying Lua state may raise an error if the
argument arg isn’t a string, isn’t a nil and not absent.
sourcepub unsafe fn opt_byte_str<'l>(
&'l self,
arg: c_int,
default: &'l [u8]
) -> &'l [u8] ⓘ
pub unsafe fn opt_byte_str<'l>( &'l self, arg: c_int, default: &'l [u8] ) -> &'l [u8] ⓘ
Works the same as Thread::opt_chars, however it returns an array of
u8s instead of c_chars.
§Safety
The underlying Lua state may raise an error if the
argument arg isn’t a string, isn’t a nil and not absent.
sourcepub unsafe fn opt_number(&self, arg: c_int, default: Number) -> Number
pub unsafe fn opt_number(&self, arg: c_int, default: Number) -> Number
sourcepub unsafe fn opt_string<'l>(
&'l self,
arg: c_int,
default: &'l CStr
) -> &'l CStr
pub unsafe fn opt_string<'l>( &'l self, arg: c_int, default: &'l CStr ) -> &'l CStr
sourcepub unsafe fn create_ref(&self, store_index: c_int) -> c_int
pub unsafe fn create_ref(&self, store_index: c_int) -> c_int
Create and return a reference, in the table at index store_index, for
the object on the top of the stack (popping the object).
A reference is a unique integer key.
As long as you do not manually add integer keys into the table
store_index, this function ensures the uniqueness of the key it
returns.
You can retrieve an object referred by the reference r by calling
thread.raw_get_i(store_index, ref_idx).
See also Thread::destroy_ref, which frees a reference.
If the object on the top of the stack is nil, this returns the constant
REF_NIL.
The constant NO_REF is guaranteed to be different from any reference
returned.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn require(
&self,
module_name: &CStr,
open_fn: CFunction,
into_global: bool
)
pub unsafe fn require( &self, module_name: &CStr, open_fn: CFunction, into_global: bool )
If package.loaded[modname] is not true, calls the function open_fn
with the string module_name as an argument and sets the call result to
package.loaded[modname], as if that function has been called through
require.
This function leaves a copy of the module on the stack.
If into_global is true, also stores the module into the global
module_name.
§Safety
The underlying Lua state may raise an arbitrary error.
sourcepub unsafe fn set_funcs<const N: usize>(
&self,
library: &Library<'_, N>,
n_upvalues: u8
)
pub unsafe fn set_funcs<const N: usize>( &self, library: &Library<'_, N>, n_upvalues: u8 )
Registers all functions in the list library into the table on the top
of the stack (below optional upvalues).
When n_upvalues is not zero, all functions are created with
n_upvalues upvalues, initialized with copies of the values previously
pushed on the stack on top of the library table.
These values are popped from the stack after the registration.
See also Library.
§Safety
The underlying Lua state may raise a memory error.
sourcepub fn set_aux_metatable(&self, table_name: &CStr)
pub fn set_aux_metatable(&self, table_name: &CStr)
Set the metatable of the object on the top of the stack as the metatable
associated with name table_name in the registry
See also Thread::new_metatable.
sourcepub unsafe fn test_udata(
&self,
arg: c_int,
table_name: &CStr
) -> Option<NonNull<u8>>
pub unsafe fn test_udata( &self, arg: c_int, table_name: &CStr ) -> Option<NonNull<u8>>
This function works like Thread::check_udata, except that, when the
test fails, it returns None instead of raising an error.
§Safety
The underlying Lua state may raise a memory error.
sourcepub unsafe fn traceback(
&self,
of: &Thread,
message: Option<&CStr>,
level: c_int
)
pub unsafe fn traceback( &self, of: &Thread, message: Option<&CStr>, level: c_int )
Create and push a traceback of the stack of thread of.
If message os Some, it is appended at the beginning of the traceback.
level tells at which level to start the traceback.
§Safety
The underlying Lua state may raise a memory error.
Examples found in repository?
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
unsafe extern "C" fn l_err_handler(l: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(l);
if let Some(msg) = lua.to_string(1) {
lua.traceback(&lua, Some(msg), 1);
return 1
}
let ok = lua.run_managed(|mut mg| {
mg.call_metamethod(1, cstr!("__tostring"))
});
if ok && lua.type_of(-1) == LuaType::String {
return 1
}
lua_push_fmt_string!(lua, "(error object is a %s value)", lua.type_name_of(1));
1
}sourcepub fn type_error(&self, arg: c_int, type_name: &CStr) -> !
pub fn type_error(&self, arg: c_int, type_name: &CStr) -> !
Raise a type error for the argument arg of the C function that called
it, using a standard message;
type_name is a “name” for the expected type.
This function never returns.
sourcepub fn type_name_of<'l>(&'l self, index: c_int) -> &'l CStr
pub fn type_name_of<'l>(&'l self, index: c_int) -> &'l CStr
Return the name of the type of the value at the given index.
Examples found in repository?
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
unsafe extern "C" fn l_err_handler(l: *mut LuaState) -> c_int {
let mut lua: LuaThread = LuaThread::from_ptr(l);
if let Some(msg) = lua.to_string(1) {
lua.traceback(&lua, Some(msg), 1);
return 1
}
let ok = lua.run_managed(|mut mg| {
mg.call_metamethod(1, cstr!("__tostring"))
});
if ok && lua.type_of(-1) == LuaType::String {
return 1
}
lua_push_fmt_string!(lua, "(error object is a %s value)", lua.type_name_of(1));
1
}sourcepub fn destroy_ref(&self, store_index: c_int, ref_idx: c_int)
pub fn destroy_ref(&self, store_index: c_int, ref_idx: c_int)
Release the reference ref_idx from the table at index store_index.
If ref_idx is LUA_NOREF or LUA_REFNIL, luaL_unref does nothing.
The entry is removed from the table, so that the referred object can be
collected.
The reference ref_idx is also freed to be used again.
See also Thread::create_ref.
sourcepub unsafe fn where_str(&self, level: c_int)
pub unsafe fn where_str(&self, level: c_int)
Push onto the stack a string identifying the current position of the
control at level level in the call stack.
Typically, this string has the following format:
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called
the running function, etc.
This function is used to build a prefix for error messages.
§Safety
The underlying Lua state may raise a memory error.
Trait Implementations§
source§impl<const ID_SIZE: usize> Allocator for Lua<ID_SIZE>
impl<const ID_SIZE: usize> Allocator for Lua<ID_SIZE>
source§fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
source§unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout)
ptr. Read moresource§fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError>
allocate, but also ensures that the returned memory is zero-initialized. Read moresource§unsafe fn grow(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
source§unsafe fn grow_zeroed(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout
) -> Result<NonNull<[u8]>, AllocError>
unsafe fn grow_zeroed( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout ) -> Result<NonNull<[u8]>, AllocError>
grow, but also ensures that the new contents are set to zero before being
returned. Read more