pub struct LuaState(/* private fields */);Expand description
Opaque container of the state of a Lua interpreter and entry point to the LuaJIT C API.
See the top-level documentation for details on how to access LuaState.
Most functions assume you have a general understanding of the virtual stack the Lua interpreter uses. If not, refer to §3.1 and §3.2.
A LuaState (and its wrapped pointer) should always be valid (unless unsafe constructors are used incorrectly) and will be treated as such.
(Most of the methods’ documentation below, and a few other places, has been written using the Lua 5.1 Reference Manual as reference: Copyright © 2006–2012 Lua.org, PUC-Rio. Licensed under the MIT license.)
Implementations§
Source§impl LuaState
State handling functions.
impl LuaState
State handling functions.
Sourcepub const fn as_ptr(&self) -> *mut lua_State
pub const fn as_ptr(&self) -> *mut lua_State
Returns the underlying raw lua_State pointer.
This can be used to pass the LuaState to raw ffi functions.
The caller must ensure that the LuaState outlives the pointer this function returns, or else it will end up dangling.
The returned pointer should also not be passed to functions that might invalidate the LuaState (like lua_close).
Sourcepub unsafe fn access_mut<T>(&self, f: impl FnOnce(&mut Self) -> T) -> T
pub unsafe fn access_mut<T>(&self, f: impl FnOnce(&mut Self) -> T) -> T
Grants temporary mutable access to the LuaState from an immutable reference.
This function should be used seldomly.
§Safety
f must not pop any pre-existing element and any element pushed onto the stack by f should be popped before the function ends.
(Not popping all pushed elements currently only constitutes a logic error, but this may change in the future and should not be relied upon unless necessary.)
Source§impl LuaState
Nil (& none) related functions.
impl LuaState
Nil (& none) related functions.
Sourcepub fn is_nil(&self, index: i32) -> bool
pub fn is_nil(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is nil, false otherwise.
Sourcepub fn is_none(&self, index: i32) -> bool
pub fn is_none(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is invalid (out of bounds), false otherwise.
Sourcepub fn is_none_or_nil(&self, index: i32) -> bool
pub fn is_none_or_nil(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is nil or invalid (out of bounds), false otherwise.
Sourcepub fn push_nil(&mut self)
pub fn push_nil(&mut self)
Pushes nil onto the stack.
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn return_nil(self) -> AmountReturned
pub fn return_nil(self) -> AmountReturned
Finishes the currently called CFunction, returning nil to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
To return no value at all instead of nil, see LuaState::return_none.
(There is a small difference, but it’s usually negligible.)
Sourcepub fn return_none(self) -> AmountReturned
pub fn return_none(self) -> AmountReturned
Finishes the currently called CFunction, returning no value to the caller.
This is currently effectively the same as just returning AmountReturned::NONE.
To return nil instead of no value at all, see LuaState::return_nil.
(There is a small difference, but it’s usually negligible.)
Examples found in repository?
23extern "C-unwind" fn push(mut lua: LuaState) -> AmountReturned {
24 let n = lua.check_number(2);
25 let vec = check_vec_mut(&mut lua);
26
27 vec.push(n);
28
29 lua.return_none()
30}
31
32extern "C-unwind" fn pop(mut lua: LuaState) -> AmountReturned {
33 let vec = check_vec_mut(&mut lua);
34
35 match vec.pop() {
36 Some(n) => lua.return_number(n),
37 None => lua.return_nil(),
38 }
39}
40
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}
68
69extern "C-unwind" fn new_index(mut lua: LuaState) -> AmountReturned {
70 let i = lua.check_integer(2);
71 let new = lua.check_number(3);
72 let vec = check_vec_mut(&mut lua);
73
74 let Some(value) = vec.get_mut(i.cast_unsigned()) else { lua.error(c"invalid index"); };
75 *value = new;
76
77 lua.return_none()
78}Source§impl LuaState
Boolean related functions.
impl LuaState
Boolean related functions.
Sourcepub fn is_boolean(&self, index: i32) -> bool
pub fn is_boolean(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a boolean, false otherwise.
Sourcepub fn to_boolean(&self, index: i32) -> bool
pub fn to_boolean(&self, index: i32) -> bool
Converts the value at the given acceptable index to a boolean and returns it.
Any value besides false or nil is converted to true, false otherwise.
This conversion does not affect the element in the stack itself (it stays as is).
Sourcepub fn push_boolean(&mut self, boolean: bool)
pub fn push_boolean(&mut self, boolean: bool)
Pushes the given boolean onto the stack.
Sourcepub fn check_boolean(&self, arg_n: i32) -> bool
pub fn check_boolean(&self, arg_n: i32) -> bool
Checks if there’s a boolean at the given index arg_n and returns it.
If the check fails, LuaState::type_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Sourcepub fn opt_boolean(&self, arg_n: i32, default: bool) -> bool
pub fn opt_boolean(&self, arg_n: i32, default: bool) -> bool
Behaves exactly as LuaState::check_boolean,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn return_boolean(self, boolean: bool) -> AmountReturned
pub fn return_boolean(self, boolean: bool) -> AmountReturned
Finishes the currently called CFunction, returning the given boolean to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Source§impl LuaState
Number related functions.
impl LuaState
Number related functions.
Sourcepub fn is_number(&self, index: i32) -> bool
pub fn is_number(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a number, false otherwise.
Sourcepub fn to_number(&self, index: i32) -> f64
pub fn to_number(&self, index: i32) -> f64
Converts the value at the given acceptable index to a number and returns it.
Only numbers or strings that can be converted into numbers are accepted. Anything else will return 0.0.
This conversion does not affect the element in the stack itself (it stays as is).
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn to_number_x(&self, index: i32) -> Option<f64>
pub fn to_number_x(&self, index: i32) -> Option<f64>
Converts the value at the given acceptable index to a number and returns it.
Only numbers or strings that can be converted into numbers are accepted. Anything else will return None.
This conversion does not affect the element in the stack itself (it stays as is).
Sourcepub fn to_integer(&self, index: i32) -> isize
pub fn to_integer(&self, index: i32) -> isize
Converts the value at the given acceptable index to an integer and returns it.
Only numbers or strings that can be converted into numbers are accepted. Anything else will return 0.
If the number is not an integer, it will be truncated in an unspecified way.
This conversion does not affect the element in the stack itself (it stays as is).
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn to_integer_x(&self, index: i32) -> Option<isize>
pub fn to_integer_x(&self, index: i32) -> Option<isize>
Converts the value at the given acceptable index to an integer and returns it.
Only numbers or strings that can be converted into numbers are accepted. Anything else will return 0.
If the number is not an integer, it will be truncated in an unspecified way.
This conversion does not affect the element in the stack itself (it stays as is).
Sourcepub fn push_number(&mut self, number: f64)
pub fn push_number(&mut self, number: f64)
Pushes the given number onto the stack.
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn push_integer(&mut self, integer: isize)
pub fn push_integer(&mut self, integer: isize)
Pushes the given integer onto the stack.
Sourcepub fn check_number(&self, arg_n: i32) -> f64
pub fn check_number(&self, arg_n: i32) -> f64
Checks if there’s a number at the given index arg_n and returns it.
If the check fails, LuaState::type_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Examples found in repository?
23extern "C-unwind" fn push(mut lua: LuaState) -> AmountReturned {
24 let n = lua.check_number(2);
25 let vec = check_vec_mut(&mut lua);
26
27 vec.push(n);
28
29 lua.return_none()
30}
31
32extern "C-unwind" fn pop(mut lua: LuaState) -> AmountReturned {
33 let vec = check_vec_mut(&mut lua);
34
35 match vec.pop() {
36 Some(n) => lua.return_number(n),
37 None => lua.return_nil(),
38 }
39}
40
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}
68
69extern "C-unwind" fn new_index(mut lua: LuaState) -> AmountReturned {
70 let i = lua.check_integer(2);
71 let new = lua.check_number(3);
72 let vec = check_vec_mut(&mut lua);
73
74 let Some(value) = vec.get_mut(i.cast_unsigned()) else { lua.error(c"invalid index"); };
75 *value = new;
76
77 lua.return_none()
78}More examples
Sourcepub fn check_integer(&self, arg_n: i32) -> isize
pub fn check_integer(&self, arg_n: i32) -> isize
Checks if there’s a number at the given index arg_n and returns it as an integer.
If the check fails, LuaState::type_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Examples found in repository?
More examples
Sourcepub fn opt_number(&self, arg_n: i32, default: f64) -> f64
pub fn opt_number(&self, arg_n: i32, default: f64) -> f64
Behaves exactly as LuaState::check_number,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn opt_integer(&self, arg_n: i32, default: isize) -> isize
pub fn opt_integer(&self, arg_n: i32, default: isize) -> isize
Behaves exactly as LuaState::check_integer,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn return_number(self, number: f64) -> AmountReturned
pub fn return_number(self, number: f64) -> AmountReturned
Finishes the currently called CFunction, returning the given number to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Examples found in repository?
More examples
Sourcepub fn return_integer(self, integer: isize) -> AmountReturned
pub fn return_integer(self, integer: isize) -> AmountReturned
Finishes the currently called CFunction, returning the given integer to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Source§impl LuaState
String related functions.
impl LuaState
String related functions.
Sourcepub fn is_string(&self, index: i32) -> bool
pub fn is_string(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a string (or number convertible to string), false otherwise.
Sourcepub fn to_string(&self, index: i32) -> Option<&str>
pub fn to_string(&self, index: i32) -> Option<&str>
Converts the value at the given acceptable index to a string and returns it as a string slice.
Only valid UTF-8 strings or numbers are accepted. Anything else will return None.
This function does affect the element in the stack itself: numbers will be replaced by the converted string of said number.
To instead obtain a printable representation of any value, see LuaState::display.
Sourcepub fn to_byte_string(&self, index: i32) -> Option<&[u8]>
pub fn to_byte_string(&self, index: i32) -> Option<&[u8]>
Converts the value at the given acceptable index to a string and returns it as a byte slice.
Only strings or numbers are accepted. Anything else will return None.
This function does affect the element in the stack itself: numbers will be replaced by the converted string of said number.
Sourcepub fn to_cstring(&self, index: i32) -> Option<&CStr>
pub fn to_cstring(&self, index: i32) -> Option<&CStr>
Converts the value at the given acceptable index to a string and returns it as a CStr.
Only strings or numbers are accepted. Anything else will return None.
This function does affect the element in the stack itself: numbers will be replaced by the converted string of said number.
Sourcepub fn push_string(&mut self, string: impl AsRef<[u8]>)
pub fn push_string(&mut self, string: impl AsRef<[u8]>)
Pushes a copy of the given string onto the stack.
Sourcepub fn push_byte_string(&mut self, byte_string: &[u8])
pub fn push_byte_string(&mut self, byte_string: &[u8])
Pushes a copy of the given byte_string onto the stack.
Sourcepub fn push_cstring<'a>(&mut self, cstring: impl Into<Option<&'a CStr>>)
pub fn push_cstring<'a>(&mut self, cstring: impl Into<Option<&'a CStr>>)
Pushes a copy of the given cstring onto the stack.
If cstring is None, nil will be pushed onto the stack instead.
Sourcepub fn check_string(&self, arg_n: i32) -> &str
pub fn check_string(&self, arg_n: i32) -> &str
Checks if there’s a valid UTF-8 string (or number convertible to string) at the given index arg_n and returns it as a string slice.
If the check fails, LuaState::type_error is called using arg_n.
This function has the same caveats as LuaState::to_string.
§Lua Errors
Intentionally errors if the check fails.
Sourcepub fn check_byte_string(&self, arg_n: i32) -> &[u8]
pub fn check_byte_string(&self, arg_n: i32) -> &[u8]
Checks if there’s a string (or number convertible to string) at the given index arg_n and returns it as a byte slice.
If the check fails, LuaState::type_error is called using arg_n.
This function has the same caveats as LuaState::to_cstring.
§Lua Errors
Intentionally errors if the check fails.
Sourcepub fn check_cstring(&self, arg_n: i32) -> &CStr
pub fn check_cstring(&self, arg_n: i32) -> &CStr
Checks if there’s a string (or number convertible to string) at the given index arg_n and returns it as a CStr.
If the check fails, LuaState::type_error is called using arg_n.
This function has the same caveats as LuaState::to_byte_string.
§Lua Errors
Intentionally errors if the check fails.
Sourcepub fn opt_string<'a>(&'a self, arg_n: i32, default: &'a str) -> &'a str
pub fn opt_string<'a>(&'a self, arg_n: i32, default: &'a str) -> &'a str
Behaves exactly as LuaState::check_string,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn opt_byte_string<'a>(&'a self, arg_n: i32, default: &'a CStr) -> &'a [u8]
pub fn opt_byte_string<'a>(&'a self, arg_n: i32, default: &'a CStr) -> &'a [u8]
Behaves exactly as LuaState::check_byte_string,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn opt_cstring<'a>(&'a self, arg_n: i32, default: &'a CStr) -> &'a CStr
pub fn opt_cstring<'a>(&'a self, arg_n: i32, default: &'a CStr) -> &'a CStr
Behaves exactly as LuaState::check_cstring,
but returns default instead of erroring when the element at the given index arg_n is nil (or non-existing).
Sourcepub fn return_string(self, string: impl AsRef<[u8]>) -> AmountReturned
pub fn return_string(self, string: impl AsRef<[u8]>) -> AmountReturned
Finishes the currently called CFunction, returning the given string to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Sourcepub fn return_byte_string(self, byte_string: &[u8]) -> AmountReturned
pub fn return_byte_string(self, byte_string: &[u8]) -> AmountReturned
Finishes the currently called CFunction, returning the given byte_string to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Sourcepub fn return_cstring<'a>(
self,
cstring: impl Into<Option<&'a CStr>>,
) -> AmountReturned
pub fn return_cstring<'a>( self, cstring: impl Into<Option<&'a CStr>>, ) -> AmountReturned
Finishes the currently called CFunction, returning the given cstring to the caller.
If cstring is None, nil will be returned to the caller instead.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Source§impl LuaState
Table related functions.
impl LuaState
Table related functions.
Sourcepub fn is_table(&self, index: i32) -> bool
pub fn is_table(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a table, false otherwise.
Sourcepub fn new_table(&mut self)
pub fn new_table(&mut self)
Creates a new empty table and pushes it onto the stack.
To pre-allocate elements when creating a new table, see LuaState::create_table.
Sourcepub fn create_table(&mut self, n_arr: i32, n_rec: i32)
pub fn create_table(&mut self, n_arr: i32, n_rec: i32)
Creates a new empty table and pushes it onto the stack.
The table will have n_arr array elements and n_rec non-array elements pre-allocated.
To create a new table without pre-allocating, see LuaState::new_table.
§Lua Errors
Calling this function way too many times may trigger a stack overflow.
Incredibly high values for n_arr or n_rec may instantly trigger a table overflow.
Sourcepub fn get_field(&mut self, index: i32, key: &CStr)
pub fn get_field(&mut self, index: i32, key: &CStr)
Does the equivalent of the Lua code t[key], where t is the value located at the given valid index.
The result is pushed onto the stack (even if nil).
For a function that does the same but allows any value instead of key, see LuaState::get_table.
§Lua Errors
Not every value t can be indexed: for example, if t is nil this function will error.
Indexing t may also trigger the __index metamethod which could error.
Sourcepub fn set_field(&mut self, index: i32, key: &CStr)
pub fn set_field(&mut self, index: i32, key: &CStr)
Does the equivalent of the Lua code t[key] = v, where t is the value located at the given valid index
and v is the value at the top of the stack (which is popped).
For a function that does the same but allows any value instead of key, see LuaState::set_table.
§Panics
Panics if the stack is empty.
§Lua Errors
Not every value t can be indexed: for example, if t is nil this function will error.
Indexing t may also trigger the __newindex metamethod which could error.
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn get_global(&mut self, name: &CStr)
pub fn get_global(&mut self, name: &CStr)
Gets the global named name and pushes it onto the stack (even if nil).
§Lua Errors
Indexing the global environment may trigger the __index metamethod which could error.
Sourcepub fn set_global(&mut self, name: &CStr)
pub fn set_global(&mut self, name: &CStr)
Sourcepub fn get_table(&mut self, index: i32)
pub fn get_table(&mut self, index: i32)
Does the equivalent of the Lua code t[k], where t is the value located at the given valid index
and k is the value at the top of the stack (which is popped).
The result is pushed onto the stack, replacing k (even if nil).
§Panics
Panics if the stack is empty.
§Lua Errors
Not every value t can be indexed: for example, if t is nil this function will error.
Indexing t may also trigger the __index metamethod which could error.
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn set_table(&mut self, index: i32)
pub fn set_table(&mut self, index: i32)
Does the equivalent of the Lua code t[k] = v, where t is the value located at the given valid index
and v and k are the values at the top of the stack (which are popped from the stack in said order).
§Panics
Panics if the stack does not contain both v and k (thus contains less than 2 elements).
§Lua Errors
Not every value t or k can be used: if t or k are nil this function will error.
Indexing t may also trigger the __newindex metamethod which could error.
Sourcepub fn raw_get(&mut self, index: i32)
pub fn raw_get(&mut self, index: i32)
Accesses a table similarly to LuaState::get_table, but without triggering any metamethod (see LuaState::get_table).
§Panics
Panics if the element at the given valid index is not a table or if the stack is empty.
Sourcepub fn raw_set(&mut self, index: i32)
pub fn raw_set(&mut self, index: i32)
Accesses a table similarly to LuaState::set_table, but without triggering any metamethod (see LuaState::set_table).
§Panics
Panics if the element at the given valid index is not a table or if the stack is empty.
§Lua errors
Not every value k can be used: if k is nil this function will error.
Sourcepub fn raw_geti(&mut self, index: i32, i: i32)
pub fn raw_geti(&mut self, index: i32, i: i32)
Does the equivalent of the Lua code t[i], where t is the value located at the given valid index.
The result is pushed onto the stack.
§Panics
Panics if the element at the given valid index is not a table.
Sourcepub fn raw_seti(&mut self, index: i32, i: i32)
pub fn raw_seti(&mut self, index: i32, i: i32)
Does the equivalent of the Lua code t[i] = v, where t is the value located at the given valid index
and v is the value at the top of the stack (which is popped).
§Panics
Panics if the element at the given valid index is not a table or if the stack is empty.
Sourcepub fn next(&mut self, index: i32) -> bool
pub fn next(&mut self, index: i32) -> bool
Pops the last element of the stack, treating it as the key,
and pushes onto the stack the next key-value pair from the table at the given index, returning true.
If there is no next key-value pair, then nothing is pushed and false is returned instead.
This function can be used to traverse all elements of a table, see the example below.
§Panics
Panics if the element at the given index is not a table.
§Lua Errors
If the given key is neither nil nor present in the table, this function will error.
§Examples
// Assume the table is located in the stack at index t.
lua.push_nil(); // Push the first (dummy) key.
while lua.next(t) { // Get the next key-value pair.
// (The key is located at index -2, while the value is located at index -1.)
// Use the key-value pair in some way...
lua.pop(1); // Pop the value, so that the key can be used to get the next key-value pair.
}Sourcepub unsafe fn next_unchecked(&mut self, index: i32) -> bool
pub unsafe fn next_unchecked(&mut self, index: i32) -> bool
Behaves exactly as LuaState::next, but without doing any checks.
§Safety
The element at the given index must be a table.
Sourcepub fn pairs(&self, index: i32) -> Pairs<'_> ⓘ
pub fn pairs(&self, index: i32) -> Pairs<'_> ⓘ
Returns an iterator over all key-value pairs of the table at the given index,
mimicking the behavior of Lua’s pairs function.
For each iteration, the indices of the current key-value pair are returned.
§Panics
Panics if the element at the given index is not a table.
§Examples
Printing the Lua standard library:
for (k, v) in lua.pairs(LuaState::GLOBALS_INDEX) {
println!("{}: {}", lua.display(k), lua.display(v));
if lua.is_table(v) {
for (k, v) in lua.pairs(v) {
println!("\t{}: {}", lua.display(k), lua.display(v));
}
}
}Sourcepub fn ipairs(&self, index: i32) -> IPairs<'_> ⓘ
pub fn ipairs(&self, index: i32) -> IPairs<'_> ⓘ
Returns an iterator over the indexed key-value pairs of the table at the given index,
mimicking the behavior of Lua’s ipairs function.
For each iteration, the indices of the current key-value pair are returned.
§Panics
Panics if the element at the given index is not a table.
Sourcepub fn get_metatable(&mut self, index: i32) -> bool
pub fn get_metatable(&mut self, index: i32) -> bool
Gets the metatable of the value at the given acceptable index and pushes it onto the stack, returning true.
If index is invalid or the value has no metatable, nothing is pushed and the function returns false.
Sourcepub fn set_metatable(&mut self, index: i32) -> bool
pub fn set_metatable(&mut self, index: i32) -> bool
Pops the top elemenet and sets it as the metatable of the value at the given acceptable index.
This function always returns true.
§Panics
Panics if the top element is not a table or if the stack is empty.
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn get_fenv(&mut self, index: i32)
pub fn get_fenv(&mut self, index: i32)
Gets the environment table of the value at the given index and pushes it onto the stack.
If index is invalid or the value has no environment table, nil is pushed onto the stack.
Sourcepub fn set_fenv(&mut self, index: i32) -> bool
pub fn set_fenv(&mut self, index: i32) -> bool
Pops a table from the stack and sets it as the environment table of the value at the given index, returning true.
Only functions, userdata and threads may have an environment table.
If index is invalid or the value’s type is not one listed above, the stack is still popped but the function returns false.
§Panics
Panics if the top element is not a table or if the stack is empty.
Sourcepub fn call_meta(&mut self, index: i32, method: &CStr) -> bool
pub fn call_meta(&mut self, index: i32, method: &CStr) -> bool
Calls the metamethod method from the metatable of the element at the given index.
The metamethod will receive the element itself as its only argument and its result will be pushed onto the stack, returning true.
If there is no metatable or no metamethod, nothing is pushed and this function returns false instead.
§Lua Errors
The called metamethod may error.
Source§impl LuaState
Function related functions.
impl LuaState
Function related functions.
Sourcepub const MULTI_RETURN: i32 = ffi::LUA_MULTRET
pub const MULTI_RETURN: i32 = ffi::LUA_MULTRET
When passed as the number of expected results for the called functions in LuaState::call or LuaState::pcall,
it will tell Lua to push to the stack exactly as many values as the called function returned.
Sourcepub fn return_any(self, amount: i32) -> AmountReturned
pub fn return_any(self, amount: i32) -> AmountReturned
Finishes the currently called CFunction, returning the last amount values that were pushed to the stack to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
§Panics
Panics if amount is higher than the amount of values currently held in the stack (LuaState::get_top).
§Examples
use low_luajit::{LuaState, AmountReturned};
extern "C-unwind" fn example(mut lua: LuaState) -> AmountReturned {
lua.push_number(12.3); // First value returned.
lua.push_string("abc"); // Second value returned.
lua.return_any(2)
}Examples found in repository?
More examples
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}
68
69extern "C-unwind" fn new_index(mut lua: LuaState) -> AmountReturned {
70 let i = lua.check_integer(2);
71 let new = lua.check_number(3);
72 let vec = check_vec_mut(&mut lua);
73
74 let Some(value) = vec.get_mut(i.cast_unsigned()) else { lua.error(c"invalid index"); };
75 *value = new;
76
77 lua.return_none()
78}
79
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn is_function(&self, index: i32) -> bool
pub fn is_function(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a function (either CFunction or Lua function), false otherwise.
Sourcepub fn is_cfunction(&self, index: i32) -> bool
pub fn is_cfunction(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a CFunction, false otherwise.
Sourcepub fn is_lua_function(&self, index: i32) -> bool
pub fn is_lua_function(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a Lua function, false otherwise.
Sourcepub fn to_cfunction(&self, index: i32) -> Option<lua_CFunction>
pub fn to_cfunction(&self, index: i32) -> Option<lua_CFunction>
Returns the lua_CFunction at the given index, or None if the value is anything else.
lua_CFunction is returned instead of CFunction as this function cannot determine its safety.
Additionally, this function may sometimes return None for some C functions even if LuaState::is_cfunction returns true.
If you just want to call a function, you probably want to use LuaState::call, LuaState::pcall, or LuaState::cpcall instead.
§Examples
let f = lua.to_cfunction(-1).unwrap();
// SAFETY: This function is safe to call.
unsafe { f(lua.as_ptr()) };Sourcepub fn push_cfunction(&mut self, func: CFunction)
pub fn push_cfunction(&mut self, func: CFunction)
Pushes the given CFunction func onto the stack.
To associate values with func, see LuaState::push_cclosure.
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn push_cclosure(&mut self, func: CFunction, n: u8)
pub fn push_cclosure(&mut self, func: CFunction, n: u8)
Pushes the given CFunction func onto the stack, while also associating n values to it.
To associate values with func, simply push said values before calling this function;
they will be popped but will be accessible from within func at the pseudo-indices returned by LuaState::upvalue_index.
If n is 0 this function will behave exactly as LuaState::push_cfunction.
§Panics
Panics if the stack contains less than n values currently.
Sourcepub fn register_function(&mut self, name: &CStr, func: CFunction)
👎Deprecated since 0.3.0: renamed to LuaState::register_cfunction
pub fn register_function(&mut self, name: &CStr, func: CFunction)
renamed to LuaState::register_cfunction
Behaves exactly as LuaState::register_cfunction.
Sourcepub fn register_cfunction(&mut self, name: &CStr, func: CFunction)
pub fn register_cfunction(&mut self, name: &CStr, func: CFunction)
Sourcepub fn call(&mut self, n_args: i32, n_results: i32)
pub fn call(&mut self, n_args: i32, n_results: i32)
Calls a function.
To properly call a function, follow these steps:
- Push the function onto the stack.
- Push the arguments of the function (as many as
n_args), pushing the first arg first and so on. - Call this function, which will pop the function and arguments and push the results (as many as
n_results) in the same order.
If n_results is LuaState::MULTI_RETURN (-1), all the results from the function are pushed to the stack.
If n_results is higher than the amount of values returned by the function, additional nils will be pushed to compensate.
§Panics
Panics if the stack does not contain the function itself and its arguments.
§Lua Errors
The called function itself may error, to catch any error consider using LuaState::pcall or LuaState::cpcall instead.
Additionally, this function will error if the first element popped (the function to call) is not a function.
Examples found in repository?
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}Sourcepub fn pcall(
&mut self,
n_args: i32,
n_results: i32,
error_func: i32,
) -> Result<(), PCallError>
pub fn pcall( &mut self, n_args: i32, n_results: i32, error_func: i32, ) -> Result<(), PCallError>
Calls a function in protected mode.
See LuaState::call for how to properly call a function.
If the called function does not error, this function behaves exactly like LuaState::call.
error_func should either be 0 or the index to an error handler function,
which will be called on error and its returned value will be treated as the error object instead of the original error message.
(Pesudo-indices cannot be used for error_func.)
§Panics
Panics if the stack does not contain the function itself and its arguments.
§Errors
If the called function triggers a Lua error,
Err will be returned with the appropriate PCallError and the error object is pushed onto of the stack.
Additionally, this function will error if the first element popped (the function to call)
or the element at index error_func are not functions.
Sourcepub fn cpcall<T>(
&mut self,
func: CFunction,
ud: *mut T,
) -> Result<(), PCallError>
pub fn cpcall<T>( &mut self, func: CFunction, ud: *mut T, ) -> Result<(), PCallError>
Calls the function func in protected mode with a single argument: a light userdata containing ud.
Any value returned by func will be discarded (the stack is not changed).
§Errors
If func triggers a Lua error,
Err will be returned with the appropriate PCallError and the error object is pushed onto of the stack.
Sourcepub fn dump<F: Writer>(&self, writer: F) -> Result<(), NonZeroI32>
pub fn dump<F: Writer>(&self, writer: F) -> Result<(), NonZeroI32>
Dumps the Lua function at the top of the stack as a binary chunk (CFunctions cannot be dumped).
Dumping is done by sending fragments of the chunk to the writer function, which should combine them together into the full chunk.
If an error happens during dumping, Err is returned with any non-zero number.
Reloading the chunk results in a function equivalent to the one originally dumped (see LuaState::load_bytes).
§Errors
If the top element is not a Lua function (or the stack is empty), this function will error returning 1.
writer may error and return any other non-zero number (1 included), based on its implementation.
§Examples
if lua.is_lua_function(-1) {
let mut chunk = Vec::new();
lua.dump(|_, fragment| {
chunk.extend_from_slice(fragment);
Ok(())
}).expect("this should never error");
// (Use the chunk in some way...)
}Sourcepub fn load_bytes(
&mut self,
bytes: &[u8],
chunk_name: &CStr,
) -> Result<(), LoadError>
pub fn load_bytes( &mut self, bytes: &[u8], chunk_name: &CStr, ) -> Result<(), LoadError>
Loads the given bytes as a Lua chunk named chunk_name, pushing the resulting function onto the stack (if successful).
(The resulting function is only pushed, not called.)
While chunk_name can be any value, there are some common naming conventions:
- If the name is the path to a file, it should be prefixed with
'@'. (LuaState::load_filedoes this.) - If the name is a custom identifier for the function, it should be prefixed with
'='. (AllCFunctions are named"=[C]".) - Anything else will be interpreted as if being the function’s source itself. (
LuaState::load_cstringdoes this.)
§Errors
If unable to load the given bytes,
Err will be returned with the appropriate LoadError and the error message is pushed onto the stack.
Sourcepub fn load_cstring(&mut self, cstring: &CStr) -> Result<(), LoadError>
pub fn load_cstring(&mut self, cstring: &CStr) -> Result<(), LoadError>
Loads the given cstring as a Lua chunk, pushing the resulting function onto the stack (if successful).
(The resulting function is only pushed, not called.)
The chunk will be named after the given cstring itself.
§Errors
If unable to load the given cstring,
Err will be returned with the appropriate LoadError and the error message is pushed onto the stack.
Sourcepub fn load_file(&mut self, filename: &CStr) -> Result<(), LoadError>
pub fn load_file(&mut self, filename: &CStr) -> Result<(), LoadError>
Attempts to open the file named filename and load it as a Lua chunk, pushing the resulting function onto the stack (if successful).
(The resulting function is only pushed, not called.)
The chunk will be named after the given filename itself.
§Errors
If unable to open the file or load its contents,
Err will be returned with the appropriate LoadError and the error message is pushed onto the stack.
Sourcepub fn return_cfunction(self, func: CFunction) -> AmountReturned
pub fn return_cfunction(self, func: CFunction) -> AmountReturned
Finishes the currently called CFunction, returning the given func to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Examples found in repository?
More examples
Source§impl LuaState
Userdata (full & light) related functions.
impl LuaState
Userdata (full & light) related functions.
Sourcepub fn is_userdata(&self, index: i32) -> bool
pub fn is_userdata(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is userdata (either full or light), false otherwise.
Sourcepub fn is_full_userdata(&self, index: i32) -> bool
pub fn is_full_userdata(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is full userdata, false otherwise.
Sourcepub fn is_light_userdata(&self, index: i32) -> bool
pub fn is_light_userdata(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is light userdata, false otherwise.
Sourcepub unsafe fn to_full_userdata<T>(&self, index: i32) -> &mut T
pub unsafe fn to_full_userdata<T>(&self, index: i32) -> &mut T
Converts the value at the given acceptable index to full userdata and returns a mutable reference reference to its block.
§Safety
- The type of the element in the stack must be full userdata.
Tmust be the same type used when creating this userdata.- The userdata’s value must be valid for
T. - There must not be another living reference to this userdata.
Sourcepub fn to_light_userdata<T>(&self, index: i32) -> *mut T
pub fn to_light_userdata<T>(&self, index: i32) -> *mut T
Converts the value at the given acceptable index to light userdata and returns it.
Only light and full userdata are accepted, anything else will return a null pointer.
Sourcepub fn new_full_userdata<T>(&mut self, value: T) -> &mut T
pub fn new_full_userdata<T>(&mut self, value: T) -> &mut T
Allocates a new block the size of T containing value, pushes onto the stack a new full userdata with the block’s address,
and then returns a mutable reference to said block.
Like any other Lua value, this userdata is inevitably collected by the garbage collector to be freed; but by default this is done by simply deallocating the block instead of properly dropping the value!
(This won’t result in undefined behavior, but could cause a memory leak for types that allocate dynamically or access some sort of external resource; more primitive types should not need to be properly dropped.)
This can be changed by having the __gc metamethod (which is triggered before the block is freed) drop the userdata.
For a simple way to do this, see LuaState::set_drop_gc_metamethod.
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn new_full_userdata_default<T: Default>(&mut self) -> &mut T
pub fn new_full_userdata_default<T: Default>(&mut self) -> &mut T
Behaves exactly as LuaState::new_full_userdata, but uses T’s default value as the block’s value.
Sourcepub fn new_full_userdata_uninit<T>(&mut self) -> &mut MaybeUninit<T>
pub fn new_full_userdata_uninit<T>(&mut self) -> &mut MaybeUninit<T>
Behaves exactly as LuaState::new_full_userdata, but without actually initializing the block.
Sourcepub fn push_light_userdata<T>(&mut self, pointer: *mut T)
pub fn push_light_userdata<T>(&mut self, pointer: *mut T)
Pushes the given pointer onto the stack as light userdata.
Unlike normal full userdata, light userdata is the raw pointer itself.
Sourcepub unsafe fn check_full_userdata<T>(
&self,
arg_n: i32,
userdata_type: &CStr,
) -> &mut T
pub unsafe fn check_full_userdata<T>( &self, arg_n: i32, userdata_type: &CStr, ) -> &mut T
Checks if there’s a full userdata of type userdata_type at the given index arg_n and returns it as full userdata.
Userdata is of type userdata_type when it uses the metatable stored in the registry with key userdata_type
(see LuaState::new_userdata_metatable).
If the check fails, LuaState::type_error is called using arg_n.
§Safety
Tmust be the same type used when creating this userdata.- The userdata’s value must be valid for
T. - There must not be another living reference to this userdata.
§Lua Errors
Intentionally errors if the check fails.
Sourcepub fn check_light_userdata<T>(
&self,
arg_n: i32,
userdata_type: &CStr,
) -> *mut T
pub fn check_light_userdata<T>( &self, arg_n: i32, userdata_type: &CStr, ) -> *mut T
Checks if there’s an userdata (either full or light) of type userdata_type at the given index arg_n and returns it as light userdata.
Userdata is of type userdata_type when it uses the metatable stored in the registry with key userdata_type
(see LuaState::new_userdata_metatable).
If the check fails, LuaState::type_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Additionally, light userdata that happens to be a null pointer will cause the check to erroneously fail.
Sourcepub unsafe fn test_full_userdata<T>(
&self,
arg_n: i32,
userdata_type: &CStr,
) -> Option<&mut T>
pub unsafe fn test_full_userdata<T>( &self, arg_n: i32, userdata_type: &CStr, ) -> Option<&mut T>
Behaves exactly as LuaState::check_full_userdata, but returns None instead of erroring if the check fails.
§Safety
Tmust be the same type used when creating this userdata.- The userdata’s value must be valid for
T. - There must not be another living reference to this userdata.
Sourcepub fn test_light_userdata<T>(&self, arg_n: i32, userdata_type: &CStr) -> *mut T
pub fn test_light_userdata<T>(&self, arg_n: i32, userdata_type: &CStr) -> *mut T
Behaves exactly as LuaState::check_full_userdata, but returns a null pointer instead of erroring if the check fails.
Sourcepub fn return_light_userdata<T>(self, pointer: *mut T) -> AmountReturned
pub fn return_light_userdata<T>(self, pointer: *mut T) -> AmountReturned
Finishes the currently called CFunction, returning the given pointer as light userdata to the caller.
The LuaState wrapper is consumed to prevent invalidating the AmountReturned (the Lua state itself is left intact).
Sourcepub fn new_userdata_metatable(&mut self, userdata_type: &CStr) -> bool
pub fn new_userdata_metatable(&mut self, userdata_type: &CStr) -> bool
Pushes onto the stack the value in the registry with key userdata_type, returning false.
If no such value exists yet, a table will be set as the value (before being pushed) and true will be returned instead.
This function is used to get the metatable to be set as the metatable of the desired userdata (see LuaState::set_metatable).
§Examples
use low_luajit::{LuaState, AmountReturned};
extern "C-unwind" fn index_metamethod(lua: LuaState) -> AmountReturned {
// ...
}
extern "C-unwind" fn my_light_userdata_constructor(mut lua: LuaState) -> AmountReturned {
// ...
// Construct the light userdata.
lua.push_light_userdata(ptr);
if lua.new_userdata_metatable(c"my_light_userdata") {
// Initialize the metatable.
lua.push_cfunction(index_metamethod);
lua.set_field(-2, c"__index");
// ...
}
lua.set_metatable(-2);
lua.return_any(1)
}Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub fn get_userdata_metatable(&mut self, userdata_type: &CStr)
pub fn get_userdata_metatable(&mut self, userdata_type: &CStr)
Pushes onto the stack the value in the registry with key userdata_type, even if nil.
This value is usually an userdata’s metatable.
Sourcepub unsafe fn set_drop_gc_metamethod<T>(&mut self)
pub unsafe fn set_drop_gc_metamethod<T>(&mut self)
Sets the __gc metamethod of the metatable at the top of the stack to a special destructor metamethod.
This metamethod will drop the full userdata (that is using the metatable) before the garbage collector frees the userdata’s block.
This function is usually only necessary when the userdata’s type implements Drop,
see LuaState::new_full_userdata for more information.
§Safety
- The type of the value that uses the metatable must be full userdata.
Tmust be the same type used when creating this userdata.- The userdata’s value must be valid for
T.
These conditions should always be true when LuaState::new_full_userdata and LuaState::new_userdata_metatable are used properly.
§Lua Errors
Indexing the top element may trigger the __newindex metamethod which could error.
Additionally, this function will error if for some reason the top element is not a table but instead something that can’t be indexed.
§Examples
lua.new_full_userdata(vec![36.2, 123.456, 0.998]);
if lua.new_userdata_metatable(c"my_full_userdata") {
// SAFETY: The metatable is being used by a valid full userdata of the same type.
unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>() }
}
lua.set_metatable(-2);(For a more complete example on how to implement metatables for userdata, see LuaState::new_userdata_metatable.)
Examples found in repository?
80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Source§impl LuaState
Thread related functions.
impl LuaState
Thread related functions.
Sourcepub fn is_thread(&self, index: i32) -> bool
pub fn is_thread(&self, index: i32) -> bool
Returns true if the value at the given acceptable index is a thread, false otherwise.
Sourcepub fn push_thread(&mut self) -> bool
pub fn push_thread(&mut self) -> bool
Pushes the thread represented by this LuaState onto the stack.
Returns true if this thread is the main thread of its state, false otherwise.
Source§impl LuaState
Type related functions.
impl LuaState
Type related functions.
Sourcepub fn type_of(&self, index: i32) -> LuaType
pub fn type_of(&self, index: i32) -> LuaType
Returns the type of the value at the given index.
Invalid indices will return LuaType::None.
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn check_type(&self, arg_n: i32, type: LuaType)
pub fn check_type(&self, arg_n: i32, type: LuaType)
Checks if there’s an element of the given type at the given index arg_n and returns it.
If the check fails, LuaState::type_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Examples found in repository?
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}Source§impl LuaState
Math functions.
impl LuaState
Math functions.
Sourcepub fn concat(&mut self, n: i32)
pub fn concat(&mut self, n: i32)
Concatenates the first n elements on top of the stack, popping them in the process, and pushes the result at the top.
If n is 1 or negative, nothing happens. If n is 0, the result is an empty string.
§Panics
Panics if the stack contains less than n values currently.
§Lua Errors
Some types (like nil or boolean) may be unable to be concatenated.
Concatenating may also trigger the __concat metamethod which could error.
Sourcepub fn object_length(&self, index: i32) -> usize
pub fn object_length(&self, index: i32) -> usize
Returns the “length” of the value at the given acceptable index:
- Strings return the string’s length.
- Numbers are converted (permanently!) to a string and return the string’s length.
- Tables return the result of the length operator (
#), bypassing the__lenmetamethod. - Userdata returns the size of the allocated block.
- Anything else will always return 0.
Sourcepub fn equal(&self, index1: i32, index2: i32) -> bool
pub fn equal(&self, index1: i32, index2: i32) -> bool
Returns true if the two values at acceptable indices index1 and index2 are equal. Returns false if they’re not equal or invalid.
§Lua Errors
Comparing may trigger the __eq metamethod which could error.
To avoid triggering any metamethod, see LuaState::raw_equal.
Sourcepub fn raw_equal(&self, index1: i32, index2: i32) -> bool
pub fn raw_equal(&self, index1: i32, index2: i32) -> bool
Returns true if the two values at acceptable indices index1 and index2 are equal. Returns false if they’re not equal or invalid.
Unlike LuaState::equal, this function will not trigger the __eq metamethod.
Sourcepub fn less_than(&self, index1: i32, index2: i32) -> bool
pub fn less_than(&self, index1: i32, index2: i32) -> bool
Returns true if the value at acceptable index index1 is less than the value at acceptable index index2.
Returns false if they’re not equal or invalid.
§Lua Errors
Some types may be incompatible for this comparison (like comparing a boolean with a string, or nil with…anything).
Comparing may trigger the __lt metamethod which could error.
Source§impl LuaState
Error handling functions.
impl LuaState
Error handling functions.
Sourcepub fn error(&self, msg: &CStr) -> !
pub fn error(&self, msg: &CStr) -> !
Triggers a Lua error using msg as the error message (alongside file and line information).
§Lua Errors
This function always errors intentionally.
Sourcepub fn type_error(&self, arg_n: i32, type_name: &CStr) -> !
pub fn type_error(&self, arg_n: i32, type_name: &CStr) -> !
Triggers a Lua error with the following message (alongside file and line information):
bad argument #{arg_n} to '{func}' ({type_name} expected, got {arg_type})(func is retrieved from the call stack and arg_type is the type of the element at index arg_n.)
§Lua Errors
This function always errors intentionally.
Sourcepub fn arg_error(&self, arg_n: i32, extra_msg: &CStr) -> !
pub fn arg_error(&self, arg_n: i32, extra_msg: &CStr) -> !
Triggers a Lua error with the following message (alongside file and line information):
bad argument #{arg_n} to '{func}' ({extra_msg})(func is retrieved from the call stack.)
§Lua Errors
This function always errors intentionally.
Sourcepub fn location(&mut self, level: i32)
pub fn location(&mut self, level: i32)
Pushes onto the stack a string specifying the position of the function at the given level:
level 0 is the current running function, level 1 is the function that called the current running function, and so on.
The pushed string has the following format:
chunk_name:current_line:(A space is appended at the end.)
If the location of the function at the given level is unknown, or level is invalid, an empty string is pushed instead.
Sourcepub fn raw_error(&mut self) -> !
pub fn raw_error(&mut self) -> !
Triggers a Lua error, popping the top element and using it as the full error message (no file or line information is included).
If the stack is empty, a generic error message is pushed beforehand.
You probably want to use LuaState::error instead.
§Lua Errors
This function always errors intentionally.
Source§impl LuaState
Stack (& indices) related functions.
impl LuaState
Stack (& indices) related functions.
Sourcepub const REGISTRY_INDEX: i32 = ffi::LUA_REGISTRYINDEX
pub const REGISTRY_INDEX: i32 = ffi::LUA_REGISTRYINDEX
Pseudo-index to the registry: a pre-defined table that C/Rust can use to store whatever it needs.
Other loaded C/Rust modules may use this table too, thus you should make your keys unique to avoid collisions (by using the module name itself for example).
The integer keys of the registry are used internally by Lua, and should not be touched.
Sourcepub const ENVIRONMENT_INDEX: i32 = ffi::LUA_ENVIRONINDEX
pub const ENVIRONMENT_INDEX: i32 = ffi::LUA_ENVIRONINDEX
Pseudo-index to the environment of the running CFunction.
Sourcepub const GLOBALS_INDEX: i32 = ffi::LUA_GLOBALSINDEX
pub const GLOBALS_INDEX: i32 = ffi::LUA_GLOBALSINDEX
Pseudo-index to the thread environment: the table containing all the global variables (_G).
Sourcepub fn pop(&mut self, amount: i32)
pub fn pop(&mut self, amount: i32)
Pops amount elements from the stack.
If amount is 0, nothing happens.
Negative values of amount are allowed, behaving the same way as passing abs(amount) - 1 to LuaState::set_top.
§Panics
Panics if the stack contains less than amount values currently.
Sourcepub fn check_stack(&mut self, extra: i32, extra_msg: &CStr)
pub fn check_stack(&mut self, extra: i32, extra_msg: &CStr)
Grow the stack to be large enough to hold extra more elements. Does nothing if the stack is already large enough.
If the stack failed to grow to the desired size, this function will error using extra_msg as the error message.
This function never shrinks the stack.
§Lua Errors
Intentionally errors if the stack fails to grow.
Sourcepub fn try_check_stack(&mut self, extra: i32) -> bool
pub fn try_check_stack(&mut self, extra: i32) -> bool
Attempts to grow the stack to be large enough to hold extra more elements. Does nothing if the stack is already large enough.
Returns false if it failed to grow the stack to the desired size, true otherwise.
This function never shrinks the stack.
Sourcepub fn get_top(&self) -> i32
pub fn get_top(&self) -> i32
Returns the index of the top element (last inserted) in the stack.
This also equals the amount of elements in the stack.
Examples found in repository?
More examples
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}80extern "C-unwind" fn constructor(mut lua: LuaState) -> AmountReturned {
81 let mut vec = Vec::new();
82
83 // Initialize the vector if the called passed some numbers.
84 for i in 1..=lua.get_top() {
85 vec.push(lua.to_number(i));
86 }
87
88 // Push the vector to the stack as userdata.
89 lua.new_full_userdata::<Vec<f64>>(vec);
90
91 // Set the vector's metatable, initializing the metatable itself if's been first created.
92 if lua.new_userdata_metatable(NUM_VECTOR_TYPE_NAME) {
93 // Vectors allocate their own memory, so we need to have them be dropped when garbage collected.
94 // SAFETY: The metatable is being used by a valid full userdata of the same type.
95 unsafe { lua.set_drop_gc_metamethod::<Vec<f64>>(); }
96
97 // __tostring metamethod.
98 lua.push_cfunction(to_string);
99 lua.set_field(-2, c"__tostring");
100
101 // __index metamethod.
102 lua.push_cfunction(index);
103 lua.set_field(-2, c"__index");
104
105 // __newindex metamethod.
106 lua.push_cfunction(new_index);
107 lua.set_field(-2, c"__newindex");
108 }
109 lua.set_metatable(-2);
110
111 lua.return_any(1)
112}Sourcepub const fn upvalue_index(n: u8) -> i32
pub const fn upvalue_index(n: u8) -> i32
Returns the pseudo-index to the upvalue #n (i.e. upvalue_index(1) returns the pseudo-index to the first upvalue).
This function does not check if the upvalue exists, it just returns its hypothethical pseudo-index.
If n is 0, this function will instead return LuaState::GLOBALS_INDEX.
Sourcepub fn is_index_valid(&self, index: i32) -> bool
pub fn is_index_valid(&self, index: i32) -> bool
Returns a boolean stating if index is a valid index.
index is valid if 1 ≤ abs(index) ≤ top.
This function only checks if index is valid, not acceptable!
Sourcepub fn is_index_ok(&self, index: i32) -> bool
pub fn is_index_ok(&self, index: i32) -> bool
Returns a boolean stating if index is an “ok” index.
index is “ok” if abs(index) ≤ top.
This function is used internally for assertions.
Sourcepub fn to_pointer(&self, index: i32) -> *const ()
pub fn to_pointer(&self, index: i32) -> *const ()
Converts the value at the given acceptable index to a generic pointer and returns it.
Only userdata, tables, and functions are accepted. Anything else will return a null pointer.
There is no intended way to convert the pointer back to its original value.
Sourcepub fn push_value(&mut self, index: i32)
pub fn push_value(&mut self, index: i32)
Pushes a copy of the value at the given valid index onto the stack.
If index is out of bounds, nil is pushed onto the stack.
Examples found in repository?
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}Sourcepub fn insert(&mut self, index: i32)
pub fn insert(&mut self, index: i32)
Pops the top element and inserts it at the given valid index, shifting up the other elements to make space.
This function will do nothing if index is 0.
To replace the element located at index instead of shifting them up, see LuaState::replace.
§Panics
Panics if index is out of bounds.
(Pseudo-indices are out of bounds as they are not real indices.)
Examples found in repository?
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}More examples
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn replace(&mut self, index: i32)
pub fn replace(&mut self, index: i32)
Pops the top element and inserts it at the given valid index, replacing the element that was previously located at index.
If index is zero, the top element is effectively removed.
To shift up the other elements instead of replacing it, see LuaState::insert.
§Panics
Panics if index is out of bounds.
(Pseudo-indices are out of bounds as they are not real indices.)
Sourcepub fn remove(&mut self, index: i32)
pub fn remove(&mut self, index: i32)
Removes the element at the given valid index, shifting down the other elements to fill the gap.
§Panics
Panics if index is out of bounds or 0.
(Pseudo-indices are out of bounds as they are not real indices.)
Examples found in repository?
3extern "C-unwind" fn join(mut lua: LuaState) -> AmountReturned {
4 // Check that the first argument is a function.
5 lua.check_type(1, LuaType::Function);
6
7 let top = lua.get_top();
8
9 // Move the function to the top of the stack and call it to have all its returned values pushed onto the stack.
10 lua.push_value(1);
11 lua.remove(1);
12 lua.call(0, LuaState::MULTI_RETURN);
13
14 // The values returned by the function should come *before* join's arguments, so let's move them back to the bottom of the stack.
15 let final_top = lua.get_top();
16 for _ in top..=final_top {
17 lua.insert(1);
18 }
19
20 // Return all the values in the stack.
21 lua.return_any(final_top)
22}Sourcepub fn copy(&mut self, from_index: i32, to_index: i32)
pub fn copy(&mut self, from_index: i32, to_index: i32)
Copies the element at index from_index into the valid index to_index, replacing the element that was previously located at to_index.
If from_index is out of bounds, the element located at to_index will be replaced with nil.
§Panics
Panics if to_index is out of bounds.
Sourcepub fn check_any(&self, arg_n: i32)
pub fn check_any(&self, arg_n: i32)
Checks if there’s an element of any type (including nil) at the given index arg_n.
If the check fails, LuaState::arg_error is called using arg_n.
§Lua Errors
Intentionally errors if the check fails.
Source§impl LuaState
Module related functions.
impl LuaState
Module related functions.
Sourcepub fn return_module(self, list: &[Reg]) -> AmountReturned
pub fn return_module(self, list: &[Reg]) -> AmountReturned
Pushes onto the stack a table filled with all the functions contained in list and finishes the currently called CFunction.
The returned AmountReturned will always be 1, which will make Lua return the pushed table to the caller.
This function can be handy to quickly return your module’s functions from your luaopen_crate_name function.
§Panics
Panics if list does not have the Reg::END terminator at its end.
(reg! automatically appends the terminator for you.)
§Examples
extern "C-unwind" fn foo(lua: LuaState) -> AmountReturned {
// ...
}
extern "C-unwind" fn bar(lua: LuaState) -> AmountReturned {
// ...
}
#[unsafe(no_mangle)]
extern "C-unwind" fn luaopen_crate_name(lua: LuaState) -> AmountReturned {
lua.return_module(reg![foo, bar])
}Sourcepub fn register_module<'a>(
&mut self,
name: impl Into<Option<&'a CStr>>,
list: &[Reg],
)
pub fn register_module<'a>( &mut self, name: impl Into<Option<&'a CStr>>, list: &[Reg], )
Pushes onto the stack a new table filled with all the functions contained in list.
This table is then set as the value of a global named name and of package.loaded[name].
If package.loaded[name] already contains a table, said table will be used instead of creating a new table
(it will still be pushed onto the stack).
If name is None, this function will instead simply use the (pre-existing) top element as the table to fill.
(In this case the table will not be set as the value of neither a global nor of package.loaded[name].)
All paths will result in the filled table being the top element.
§Panics
Panics if list does not have the Reg::END terminator at its end.
(reg! automatically appends the terminator for you.)
§Lua Errors
Indexing most of the aformentioned tables may trigger the __newindex metamethod which could error.
Sourcepub fn new_module(&mut self, list: &[Reg])
pub fn new_module(&mut self, list: &[Reg])
Creates a new table and pushes it onto the stack.
This table will be filled with all the functions contained in list.
To automatically return this table to the caller, see LuaState::return_module.
For a function that only pushes an empty pre-allocated (for list) table to the stack, see LuaState::new_module_table.
§Panics
Panics if list does not have the Reg::END terminator at its end.
(reg! automatically appends the terminator for you.)
Examples found in repository?
41extern "C-unwind" fn index(mut lua: LuaState) -> AmountReturned {
42 let vec = check_vec(&lua);
43
44 match lua.type_of(2) {
45 // The index is a string, so it's probably trying to access the vector's methods.
46 // Let's quickly generate the methods' table and get the requested method.
47 // (It would be better to cache it somewhere, but for this example this is fine enough.)
48 LuaType::String => {
49 // We can create the table as a "module" for convenience. This way we can quickly add more methods if needed.
50 lua.new_module(reg![push, pop]);
51
52 // The key needs to be the top element, so we move the table to the 2nd element instead.
53 lua.insert(2);
54
55 // Index the method table.
56 lua.get_table(2);
57 },
58
59 // If the index is just a number, attempt to index the vector itself
60 LuaType::Number if let Some(n) = vec.get(lua.to_integer(2).cast_unsigned()) => lua.push_number(*n),
61
62 // Invalid index, return nil.
63 _ => lua.push_nil(),
64 }
65
66 lua.return_any(1)
67}Sourcepub fn new_module_table(&mut self, list: &[Reg])
pub fn new_module_table(&mut self, list: &[Reg])
Creates a new empty table and pushes it onto the stack.
This table will have as many elements as there are function in list pre-allocated.
For a function that both pushes a pre-allocated table to the stack and fills it with list’s functions, see LuaState::new_module.
§Panics
Panics if list does not have the Reg::END terminator at its end.
(reg! automatically appends the terminator for you.)
Source§impl LuaState
Garbage collector handling functions.
impl LuaState
Garbage collector handling functions.
See §2.10 for more information on the garbage collector.
Sourcepub fn gc(&self, what: i32, data: i32) -> i32
pub fn gc(&self, what: i32, data: i32) -> i32
Generic garbage collector controller function.
This function’s behavior changes based on the given what. Use the LUA_GC* constants found in the ffi module.
Invalid what values return -1.
Sourcepub fn gc_restart(&self)
pub fn gc_restart(&self)
Restarts the garbage collector.
Sourcepub fn gc_collect(&self)
pub fn gc_collect(&self)
Performs a full garbage collection cycle.
Sourcepub fn gc_count_b(&self) -> i32
pub fn gc_count_b(&self) -> i32
Returns the remainder of dividing the current amount of bytes of memory in use by Lua by 1024.
Sourcepub fn gc_step(&self, size: i32) -> bool
pub fn gc_step(&self, size: i32) -> bool
Performs an incremental step of garbage collection.
size controls the step “size” in a non-specific way (larger values -> larger steps).
This function returns true if it finished a garbage collection cycle, false otherwise.
Sourcepub fn gc_set_pause(&self, pause: i32) -> i32
pub fn gc_set_pause(&self, pause: i32) -> i32
Sets pause as the new pause value of the collector, returning the previous value.
Sourcepub fn gc_set_step_multiplier(&self, step_multiplier: i32) -> i32
pub fn gc_set_step_multiplier(&self, step_multiplier: i32) -> i32
Sets step_multiplier as the new step multiplier value of the collector, returning the previous value.
Sourcepub fn gc_is_running(&self) -> bool
pub fn gc_is_running(&self) -> bool
Returns true if the garbage collector is currently running, false otherwise.
Source§impl LuaState
Debug interface functions.
impl LuaState
Debug interface functions.
See §3.8 for more information on the Debug interface.
Sourcepub fn get_info(&mut self, what: &CStr, info: &mut DebugInfo) -> bool
pub fn get_info(&mut self, what: &CStr, info: &mut DebugInfo) -> bool
Requests information about a specified function. The retrieved information will be stored in info.
There are three ways to specify a function:
- From the interpreter runtime stack by using
LuaState::get_stack. - From the top element by adding
'>'at the start ofwhat(the element will be popped). - Pre-specified when
DebugInfois received from anHook’s arguments (seeHook).
The type of information requested is based on which “selectors” (characters) what contains:
'n'will setDebugInfo::nameandDebugInfo::name_what.'S'will setDebugInfo::source,DebugInfo::short_source,DebugInfo::line_defined,DebugInfo::last_line_defined, andDebugInfo::what.'l'will setDebugInfo::current_line.'u'will setDebugInfo::n_upvalues.'f'pushes onto the stack the specified function itself.'L'pushes onto the stack a table whose indices are the number of valid lines (with associated code) of the specified function.
(The selectors are executed based on their order in what.)
If an invalid character is present in what, or '>' is used and the top elemenet is not a function,
this function will end early and return false. true is returned otherwise.
§Panics
Panics if none of the three ways of specifying a function are attempted.
Sourcepub fn get_stack(&self, level: i32, info: &mut DebugInfo) -> bool
pub fn get_stack(&self, level: i32, info: &mut DebugInfo) -> bool
Prepare the given info to specify the function at the given level:
level 0 is the current running function, level 1 is the function that called the current running function, and so on.
If the given level is invalid, info is not prepared and the function returns false. true is returned otherwise.
This function is meant to be used alongside LuaState::get_info to get information about the specified function.
Sourcepub fn get_local(&mut self, info: Option<&DebugInfo>, n: i32) -> Option<&CStr>
pub fn get_local(&mut self, info: Option<&DebugInfo>, n: i32) -> Option<&CStr>
Get information about a local variable of a specified function.
There are three ways to specify a function:
- From the interpreter runtime stack by using
LuaState::get_stack. - From the top element by passing
Noneforinfo(the element will not be popped). - Pre-specified when
DebugInfois received from anHook’s arguments (seeHook).
n selects which local to get, 1 being the first local and so on until the last local.
Negative values of n can be used to get vararg arguments.
When info is Some, this function will push to the stack the local’s value and return the local’s name.
Otherwise only the name is returned and nothing is pushed to the stack.
Invalid values of n or the top element not being a function (when info is None)
will result in the function returning None and pushing nothing to the stack.
If the returned name is enclosed in round brackets, the queried local is an internal variable.
§Panics
Panics if none of the three ways of specifying a function are attempted.
Sourcepub fn set_local(&mut self, info: &DebugInfo, n: i32) -> Option<&CStr>
pub fn set_local(&mut self, info: &DebugInfo, n: i32) -> Option<&CStr>
Sets the value of a local variable of a specified function to the value of the top element (which is popped), returning the local’s name.
There are two ways to specify a function:
- From the interpreter runtime stack by using
LuaState::get_stack. - Pre-specified when
DebugInfois received from anHook’s arguments (seeHook).
n selects which local to get, 1 being the first local and so on until the last local.
Negative values of n can be used to get vararg arguments.
Invalid values of n will result in the function returning None and not changing any local, but the top element will still be popped!
If the returned name is enclosed in round brackets, the changed local is an internal variable.
§Panics
Panics if none of the two ways of specifying a function are attempted or if the stack is empty.
Sourcepub fn get_upvalue(&mut self, func_index: i32, n: u8) -> Option<&CStr>
pub fn get_upvalue(&mut self, func_index: i32, n: u8) -> Option<&CStr>
Get information about the nth upvalue of the function at index func_index.
The upvalue’s value is pushed onto the stack and its name is returned.
If the nth upvalue doesn’t exist or the element at index func_index is not a function,
None is returned and nothing is pushed onto the stack.
If the function is a CFunction, the returned upvalue name will be an empty string.
Sourcepub fn set_upvalue(&mut self, func_index: i32, n: u8) -> Option<&CStr>
pub fn set_upvalue(&mut self, func_index: i32, n: u8) -> Option<&CStr>
Sets the value of the nth upvalue of the function at index func_index to the value of the top element (which is popped),
returning the upvalue’s name.
If the nth upvalue doesn’t exist or the element at index func_index is not a function,
None is returned and the upvalue is not changed (the top element will not be popped).
§Panics
Panics if the stack is empty.
Sourcepub fn is_function_upvalue(&self, func_index: i32, n: u8) -> bool
pub fn is_function_upvalue(&self, func_index: i32, n: u8) -> bool
Returns true if the nth upvalue of the function at index func_index exists, false otherwise.
Sourcepub fn upvalue_id(&self, func_index: i32, n: u8) -> *mut ()
pub fn upvalue_id(&self, func_index: i32, n: u8) -> *mut ()
Returns an unique generic pointer for the nth upvalue of the function at index func_index.
Different upvalues will always return different pointers, thus the pointers can be compared to see if different functions share the same upvalue.
If func_index or n are invalid a null pointer will be returned instead.
There is no intended way to convert the pointer to the upvalue itself.
Sourcepub fn set_hook(&self, hook: Hook, mask: i32, count: i32)
pub fn set_hook(&self, hook: Hook, mask: i32, count: i32)
Sets a new debugging Hook function, replacing the previous hook (see Hook).
mask specifies which HookEvents can call hook,
the “mask value” of an HookEvent can be obtained from HookEvent::as_mask or from the HookEvent::MASK_* constants.
Different mask values can be bit or’d together so that the hook can be called from different events.
If mask is 0 or invalid, this function behaves the same as LuaState::unset_hook.
If HookEvent::Count is one of the possible events for this hook, count specifies the amounts of instructions inbetween each call
(it’s ignored otherwise).
§Examples
extern "C-unwind" fn example_hook(lua: LuaState, info: &mut DebugInfo) {
println!("Hook called by {:?}!", info.event());
}
lua.set_hook(example_hook, HookEvent::MASK_CALL | HookEvent::MASK_RETURN, 0);Sourcepub fn unset_hook(&self)
pub fn unset_hook(&self)
Disables the current Hook, without replacing it with another.
To replace it with a new one instead, see LuaState::set_hook.
Sourcepub fn get_hook_mask(&self) -> i32
pub fn get_hook_mask(&self) -> i32
Returns the current Hook’s mask value.
See LuaState::set_hook for more information.
Sourcepub fn set_hook_mask(&self, mask: i32)
pub fn set_hook_mask(&self, mask: i32)
Sets the current Hook’s mask value.
See LuaState::set_hook for more information.
Sourcepub fn get_hook_count(&self) -> i32
pub fn get_hook_count(&self) -> i32
Returns the current Hook’s “count” (not the current count, simply the value that was specified).
See LuaState::set_hook for more information.
Sourcepub fn set_hook_count(&self, count: i32)
pub fn set_hook_count(&self, count: i32)
Sets the current Hook’s “count” (resetting its progress).
See LuaState::set_hook for more information.
Source§impl LuaState
StringBuffer initialization function.
impl LuaState
StringBuffer initialization function.
Sourcepub fn init_buffer<'a>(
&'a mut self,
buffer: Pin<&'a mut MaybeUninit<StringBuffer<'a>>>,
) -> Pin<&'a mut StringBuffer<'a>>
pub fn init_buffer<'a>( &'a mut self, buffer: Pin<&'a mut MaybeUninit<StringBuffer<'a>>>, ) -> Pin<&'a mut StringBuffer<'a>>
Initializes the given buffer, returning a pinned mutable reference to it.
Source§impl LuaState
JIT compiler engine handling functions.
impl LuaState
JIT compiler engine handling functions.
Sourcepub fn jit_set_mode(&self, index: i32, mode: i32) -> bool
pub fn jit_set_mode(&self, index: i32, mode: i32) -> bool
Generic JIT compiler engine mode controller function.
mode should be a LUAJIT_MODE_* constant (see the ffi module) or’d with a JITMode flag.
Returns true on success, false otherwise.
§Panics
Panics if mode uses LUAJIT_MODE_FUNC, LUAJIT_MODE_ALLFUNC, or LUAJIT_MODE_ALLSUBFUNC and index is out of bounds.
Additionally, this function will always panic if mode uses LUAJIT_MODE_WRAPCFUNC.
Sourcepub fn jit_set_engine(&self, mode: impl Into<JITMode>) -> bool
pub fn jit_set_engine(&self, mode: impl Into<JITMode>) -> bool
Sets the entire JIT compiler on or off or flushes the cached compiled code.
This function always returns true unless the version of LuaJIT being used was compiled without the JIT compiler.
Sourcepub fn jit_set_function(
&self,
index: i32,
mode: impl Into<JITMode>,
to_self: bool,
to_subs: bool,
) -> bool
pub fn jit_set_function( &self, index: i32, mode: impl Into<JITMode>, to_self: bool, to_subs: bool, ) -> bool
Sets JIT compilation on or off, or flushes already compiled code, for the specified functions.
If to_self is true, the function at the given index will be affected.
If to_subs is true, the sub-functions of the function at the given index will be affected.
If index is 0, the function that called the currently running CFunction will be used in the above cases.
(This function only applies to Lua functions, as CFunctions cannot be JIT compiled.)
This function will return true if at least one function was affected, false otherwise.
If the version of LuaJIT being used was compiled without the JIT compiler no function can be affected.
§Panics
Panics if index is out of bounds.
Sourcepub fn jit_flush_trace(&self, trace: u32)
pub fn jit_flush_trace(&self, trace: u32)
Flushes the given root trace and all of its side traces from the cache.
The code for the trace will be retained as long as there are any other traces which link to it.