Skip to main content

LuaState

Struct LuaState 

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

Source

pub const unsafe fn from_ptr(ptr: *mut lua_State) -> Self

Wraps a pre-existing raw lua_State pointer.

§Safety

ptr must be a valid pointer of an already existing state, as all other methods will assume it to be so.

Additionally, there must not be an existing accessible LuaState that is already using this pointer.

Source

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

Source

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

pub unsafe fn close(self)

Destroys all objects and frees all dynamic memory of the state.

§Safety

Can only be called if this LuaState is not being used anywhere else.

If your crate is a Lua module, this function must not return back to the Lua interpreter (as it would no longer exist).

Source

pub fn version() -> &'static f64

Returns a reference to a number that represents the version of Lua.

For LuaJIT, this should always returns 501 (which represents 5.1, the Lua version LuaJIT is based on).

Source§

impl LuaState

Nil (& none) related functions.

Source

pub fn is_nil(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is nil, false otherwise.

Source

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.

Source

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.

Source

pub fn push_nil(&mut self)

Pushes nil onto the stack.

Examples found in repository?
examples/num_vector.rs (line 63)
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}
Source

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

Examples found in repository?
examples/num_vector.rs (line 37)
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}
Source

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?
examples/num_vector.rs (line 29)
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.

Source

pub fn is_boolean(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is a boolean, false otherwise.

Source

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

Source

pub fn push_boolean(&mut self, boolean: bool)

Pushes the given boolean onto the stack.

Source

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.

Source

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

Source

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

Examples found in repository?
examples/simple.rs (line 28)
24extern "C-unwind" fn is_ascii(lua: LuaState) -> AmountReturned {
25	let string = lua.check_string(1);
26
27	let is_ascii = string.is_ascii();
28	lua.return_boolean(is_ascii)
29}
Source§

impl LuaState

Number related functions.

Source

pub fn is_number(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is a number, false otherwise.

Source

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?
examples/num_vector.rs (line 85)
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

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

Source

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?
examples/num_vector.rs (line 60)
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}
Source

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

Source

pub fn push_number(&mut self, number: f64)

Pushes the given number onto the stack.

Examples found in repository?
examples/num_vector.rs (line 60)
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}
Source

pub fn push_integer(&mut self, integer: isize)

Pushes the given integer onto the stack.

Examples found in repository?
examples/simple.rs (line 19)
15extern "C-unwind" fn count_bits(mut lua: LuaState) -> AmountReturned {
16	let number = lua.check_integer(1);
17
18	// Push and return the amount of zeros and ones in the integer.
19	lua.push_integer(number.count_zeros() as isize);
20	lua.push_integer(number.count_ones() as isize);
21	lua.return_any(2)
22}
Source

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?
examples/num_vector.rs (line 24)
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
Hide additional examples
examples/simple.rs (line 8)
3extern "C-unwind" fn sum(lua: LuaState) -> AmountReturned {
4	let mut result = 0.0;
5
6	// Sum up all the arguments together, erroring if a non-number is passed.
7	for i in 1..=lua.get_top() {
8		result += lua.check_number(i);
9	}
10
11	lua.return_number(result)
12}
Source

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?
examples/simple.rs (line 16)
15extern "C-unwind" fn count_bits(mut lua: LuaState) -> AmountReturned {
16	let number = lua.check_integer(1);
17
18	// Push and return the amount of zeros and ones in the integer.
19	lua.push_integer(number.count_zeros() as isize);
20	lua.push_integer(number.count_ones() as isize);
21	lua.return_any(2)
22}
More examples
Hide additional examples
examples/num_vector.rs (line 70)
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

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

Source

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

Source

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?
examples/num_vector.rs (line 36)
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}
More examples
Hide additional examples
examples/simple.rs (line 11)
3extern "C-unwind" fn sum(lua: LuaState) -> AmountReturned {
4	let mut result = 0.0;
5
6	// Sum up all the arguments together, erroring if a non-number is passed.
7	for i in 1..=lua.get_top() {
8		result += lua.check_number(i);
9	}
10
11	lua.return_number(result)
12}
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn push_string(&mut self, string: impl AsRef<[u8]>)

Pushes a copy of the given string onto the stack.

Source

pub fn push_byte_string(&mut self, byte_string: &[u8])

Pushes a copy of the given byte_string onto the stack.

Source

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.

Source

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.

Examples found in repository?
examples/simple.rs (line 25)
24extern "C-unwind" fn is_ascii(lua: LuaState) -> AmountReturned {
25	let string = lua.check_string(1);
26
27	let is_ascii = string.is_ascii();
28	lua.return_boolean(is_ascii)
29}
Source

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.

Source

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.

Source

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

Source

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

Source

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

Source

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

Examples found in repository?
examples/num_vector.rs (line 20)
16extern "C-unwind" fn to_string(lua: LuaState) -> AmountReturned {
17	let vec = check_vec(&lua);
18
19	let string = format!("{vec:?}");
20	lua.return_string(string)
21}
Source

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

Source

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

pub fn gsub( &mut self, string: &CStr, pattern: &CStr, replacement: &CStr, ) -> &CStr

Creates a copy of string where every occurrence of pattern is replaced by replacement.

The resulting string is both pushed onto the stack and returned.

Source§

impl LuaState

Table related functions.

Source

pub fn is_table(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is a table, false otherwise.

Source

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.

Source

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.

Source

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.

Source

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?
examples/num_vector.rs (line 99)
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

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.

Source

pub fn set_global(&mut self, name: &CStr)

Pops the top element and sets it as the value of the global named name.

§Panics

Panics if the stack is empty.

§Lua Errors

Indexing the global environment may trigger the __newindex metamethod which could error.

Source

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?
examples/num_vector.rs (line 56)
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}
Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.
}
Source

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.

Source

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.

See also the Pairs struct.

§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));
        }
    }
}
Source

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.

See also the IPairs struct.

§Panics

Panics if the element at the given index is not a table.

Source

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.

Source

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?
examples/num_vector.rs (line 109)
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

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.

Source

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.

Source

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.

Source

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.

Source

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?
examples/simple.rs (line 21)
15extern "C-unwind" fn count_bits(mut lua: LuaState) -> AmountReturned {
16	let number = lua.check_integer(1);
17
18	// Push and return the amount of zeros and ones in the integer.
19	lua.push_integer(number.count_zeros() as isize);
20	lua.push_integer(number.count_ones() as isize);
21	lua.return_any(2)
22}
More examples
Hide additional examples
examples/join_varargs.rs (line 21)
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}
examples/num_vector.rs (line 66)
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}
Source

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.

Source

pub fn is_cfunction(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is a CFunction, false otherwise.

Source

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.

Source

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

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?
examples/num_vector.rs (line 98)
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

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.

Source

pub fn register_function(&mut self, name: &CStr, func: CFunction)

👎Deprecated since 0.3.0:

renamed to LuaState::register_cfunction

Behaves exactly as LuaState::register_cfunction.

Source

pub fn register_cfunction(&mut self, name: &CStr, func: CFunction)

Sets the given CFunction func as a global named name.

§Lua Errors

Indexing the global environment may trigger the __newindex metamethod which could error.

Source

pub fn call(&mut self, n_args: i32, n_results: i32)

Calls a function.

To properly call a function, follow these steps:

  1. Push the function onto the stack.
  2. Push the arguments of the function (as many as n_args), pushing the first arg first and so on.
  3. 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?
examples/join_varargs.rs (line 12)
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

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.

Source

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.

Source

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

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_file does this.)
  • If the name is a custom identifier for the function, it should be prefixed with '='. (All CFunctions are named "=[C]".)
  • Anything else will be interpreted as if being the function’s source itself. (LuaState::load_cstring does 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.

Source

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.

Source

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.

Source

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?
examples/join_varargs.rs (line 26)
25extern "C-unwind" fn luaopen_join_varargs(lua: LuaState) -> AmountReturned {
26	lua.return_cfunction(join)
27}
More examples
Hide additional examples
examples/num_vector.rs (line 116)
115extern "C-unwind" fn luaopen_num_vector(lua: LuaState) -> AmountReturned {
116	lua.return_cfunction(constructor)
117}
Source

pub fn arg_check(&self, condition: bool, arg_n: i32, extra_msg: &CStr)

If condition is false, LuaState::arg_error is called using arg_n and extra_msg. Otherwise nothing happens.

§Lua Errors

Intentionally errors if condition is false.

Source§

impl LuaState

Userdata (full & light) related functions.

Source

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.

Source

pub fn is_full_userdata(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is full userdata, false otherwise.

Source

pub fn is_light_userdata(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is light userdata, false otherwise.

Source

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.
  • T must 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.
Source

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.

Source

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?
examples/num_vector.rs (line 89)
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

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.

Source

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.

Source

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.

Source

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
  • T must 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.

Examples found in repository?
examples/num_vector.rs (line 8)
6fn check_vec(lua: &LuaState) -> &Vec<f64> {
7	// SAFETY: "numerical vector" userdata should always be valid and of this type, and there should be no other mutable reference to it.
8	unsafe { lua.check_full_userdata::<Vec<f64>>(1, NUM_VECTOR_TYPE_NAME) }
9}
10
11fn check_vec_mut(lua: &mut LuaState) -> &mut Vec<f64> {
12	// SAFETY: "numerical vector" userdata should always be valid and of this type, and there should be no other reference to it.
13	unsafe { lua.check_full_userdata::<Vec<f64>>(1, NUM_VECTOR_TYPE_NAME) }
14}
Source

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.

Source

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
  • T must 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.
Source

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.

Source

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

Source

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?
examples/num_vector.rs (line 92)
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

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.

Source

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.
  • T must 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?
examples/num_vector.rs (line 95)
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.

Source

pub fn is_thread(&self, index: i32) -> bool

Returns true if the value at the given acceptable index is a thread, false otherwise.

Source

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.

Source

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?
examples/num_vector.rs (line 44)
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}
Source

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?
examples/join_varargs.rs (line 5)
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.

Source

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.

Source

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 __len metamethod.
  • Userdata returns the size of the allocated block.
  • Anything else will always return 0.
Source

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.

Source

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.

Source

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.

Source

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.

Examples found in repository?
examples/num_vector.rs (line 74)
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

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub const ENVIRONMENT_INDEX: i32 = ffi::LUA_ENVIRONINDEX

Pseudo-index to the environment of the running CFunction.

Source

pub const GLOBALS_INDEX: i32 = ffi::LUA_GLOBALSINDEX

Pseudo-index to the thread environment: the table containing all the global variables (_G).

Source

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.

Source

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.

Source

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.

Source

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?
examples/simple.rs (line 7)
3extern "C-unwind" fn sum(lua: LuaState) -> AmountReturned {
4	let mut result = 0.0;
5
6	// Sum up all the arguments together, erroring if a non-number is passed.
7	for i in 1..=lua.get_top() {
8		result += lua.check_number(i);
9	}
10
11	lua.return_number(result)
12}
More examples
Hide additional examples
examples/join_varargs.rs (line 7)
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}
examples/num_vector.rs (line 84)
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

pub fn set_top(&mut self, index: i32)

Sets the stack top to be index.

If the new top is higher than the previous, the new elements are filled with nil.

An index of 0 removes all stack elements.

§Panics

Panics if index is a negative number and abs(index) > top.

§Lua Errors

Really high index values may cause a stack overflow.

Source

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.

Source

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!

Source

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.

Source

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.

Source

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?
examples/join_varargs.rs (line 10)
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

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?
examples/join_varargs.rs (line 17)
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
Hide additional examples
examples/num_vector.rs (line 53)
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}
Source

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

Source

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?
examples/join_varargs.rs (line 11)
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

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.

Source

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

pub fn opt<T>( &self, func: impl FnOnce(&LuaState, i32) -> T, arg_n: i32, default: T, ) -> T

Returns default when the element at the given index arg_n is nil (or non-existing).

Otherwise, func is called with self and arg_n as its arguments, returning the value func returns.

Source

pub fn display(&self, index: i32) -> impl Display + '_

Returns a printable representation of the element at the given index.

The formatting is unspecified but it loosely mimics the formatting of Lua’s tostring function. This may change in the future.

Source§

impl LuaState

Module related functions.

Source

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])
}
Examples found in repository?
examples/simple.rs (line 35)
32extern "C-unwind" fn luaopen_simple(lua: LuaState) -> AmountReturned {
33	println!("Hello from Rust!");
34
35	lua.return_module(reg![sum, count_bits, is_ascii])
36}
Source

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.

Source

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?
examples/num_vector.rs (line 50)
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}
Source

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.

See §2.10 for more information on the garbage collector.

Source

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.

Source

pub fn gc_stop(&self)

Stops the garbage collector.

Source

pub fn gc_restart(&self)

Restarts the garbage collector.

Source

pub fn gc_collect(&self)

Performs a full garbage collection cycle.

Source

pub fn gc_count(&self) -> i32

Returns the amount of memory in use by Lua, in Kbytes.

Source

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.

Source

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.

Source

pub fn gc_set_pause(&self, pause: i32) -> i32

Sets pause as the new pause value of the collector, returning the previous value.

Source

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.

Source

pub fn gc_is_running(&self) -> bool

Returns true if the garbage collector is currently running, false otherwise.

Source§

impl LuaState

Debug interface functions.

See §3.8 for more information on the Debug interface.

See also the DebugInfo struct.

Source

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 of what (the element will be popped).
  • Pre-specified when DebugInfo is received from an Hook’s arguments (see Hook).

The type of information requested is based on which “selectors” (characters) what contains:

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

Source

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.

Source

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 None for info (the element will not be popped).
  • Pre-specified when DebugInfo is received from an Hook’s arguments (see Hook).

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.

Source

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:

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn get_hook(&self) -> Option<lua_Hook>

Returns the current Hook, or None if no hook is currently enabled.

lua_Hook is returned instead of Hook as this function cannot determine its safety.

Source

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);
Source

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.

Source

pub fn get_hook_mask(&self) -> i32

Returns the current Hook’s mask value.

See LuaState::set_hook for more information.

Source

pub fn set_hook_mask(&self, mask: i32)

Sets the current Hook’s mask value.

See LuaState::set_hook for more information.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Trait Implementations§

Source§

impl Debug for LuaState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for LuaState

Source§

impl PartialEq for LuaState

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for LuaState

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.