Struct mlua::Table

source ·
pub struct Table<'lua>(/* private fields */);
Expand description

Handle to an internal Lua table.

Implementations§

source§

impl<'lua> Table<'lua>

source

pub fn set<K: IntoLua<'lua>, V: IntoLua<'lua>>( &self, key: K, value: V ) -> Result<()>

Sets a key-value pair in the table.

If the value is nil, this will effectively remove the pair.

This might invoke the __newindex metamethod. Use the raw_set method if that is not desired.

§Examples

Export a value as a global to make it usable from Lua:

let globals = lua.globals();

globals.set("assertions", cfg!(debug_assertions))?;

lua.load(r#"
    if assertions == true then
        -- ...
    elseif assertions == false then
        -- ...
    else
        error("assertions neither on nor off?")
    end
"#).exec()?;
source

pub fn get<K: IntoLua<'lua>, V: FromLua<'lua>>(&self, key: K) -> Result<V>

Gets the value associated to key from the table.

If no value is associated to key, returns the nil value.

This might invoke the __index metamethod. Use the raw_get method if that is not desired.

§Examples

Query the version of the Lua interpreter:

let globals = lua.globals();

let version: String = globals.get("_VERSION")?;
println!("Lua version: {}", version);
source

pub fn contains_key<K: IntoLua<'lua>>(&self, key: K) -> Result<bool>

Checks whether the table contains a non-nil value for key.

This might invoke the __index metamethod.

source

pub fn push<V: IntoLua<'lua>>(&self, value: V) -> Result<()>

Appends a value to the back of the table.

This might invoke the __len and __newindex metamethods.

source

pub fn pop<V: FromLua<'lua>>(&self) -> Result<V>

Removes the last element from the table and returns it.

This might invoke the __len and __newindex metamethods.

source

pub fn equals<T: AsRef<Self>>(&self, other: T) -> Result<bool>

Compares two tables for equality.

Tables are compared by reference first. If they are not primitively equals, then mlua will try to invoke the __eq metamethod. mlua will check self first for the metamethod, then other if not found.

§Examples

Compare two tables using __eq metamethod:

let table1 = lua.create_table()?;
table1.set(1, "value")?;

let table2 = lua.create_table()?;
table2.set(2, "value")?;

let always_equals_mt = lua.create_table()?;
always_equals_mt.set("__eq", lua.create_function(|_, (_t1, _t2): (Table, Table)| Ok(true))?)?;
table2.set_metatable(Some(always_equals_mt));

assert!(table1.equals(&table1.clone())?);
assert!(table1.equals(&table2)?);
source

pub fn raw_set<K: IntoLua<'lua>, V: IntoLua<'lua>>( &self, key: K, value: V ) -> Result<()>

Sets a key-value pair without invoking metamethods.

source

pub fn raw_get<K: IntoLua<'lua>, V: FromLua<'lua>>(&self, key: K) -> Result<V>

Gets the value associated to key without invoking metamethods.

source

pub fn raw_insert<V: IntoLua<'lua>>(&self, idx: Integer, value: V) -> Result<()>

Inserts element value at position idx to the table, shifting up the elements from table[idx]. The worst case complexity is O(n), where n is the table length.

source

pub fn raw_push<V: IntoLua<'lua>>(&self, value: V) -> Result<()>

Appends a value to the back of the table without invoking metamethods.

source

pub fn raw_pop<V: FromLua<'lua>>(&self) -> Result<V>

Removes the last element from the table and returns it, without invoking metamethods.

source

pub fn raw_remove<K: IntoLua<'lua>>(&self, key: K) -> Result<()>

Removes a key from the table.

If key is an integer, mlua shifts down the elements from table[key+1], and erases element table[key]. The complexity is O(n) in the worst case, where n is the table length.

For other key types this is equivalent to setting table[key] = nil.

source

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

Clears the table, removing all keys and values from array and hash parts, without invoking metamethods.

This method is useful to clear the table while keeping its capacity.

source

pub fn len(&self) -> Result<Integer>

Returns the result of the Lua # operator.

This might invoke the __len metamethod. Use the raw_len method if that is not desired.

source

pub fn raw_len(&self) -> usize

Returns the result of the Lua # operator, without invoking the __len metamethod.

source

pub fn is_empty(&self) -> bool

Returns true if the table is empty, without invoking metamethods.

It checks both the array part and the hash part.

source

pub fn get_metatable(&self) -> Option<Table<'lua>>

Returns a reference to the metatable of this table, or None if no metatable is set.

Unlike the getmetatable Lua function, this method ignores the __metatable field.

source

pub fn set_metatable(&self, metatable: Option<Table<'lua>>)

Sets or removes the metatable of this table.

If metatable is None, the metatable is removed (if no metatable is set, this does nothing).

source

pub fn set_readonly(&self, enabled: bool)

Available on crate feature luau only.

Sets readonly attribute on the table.

Requires feature = "luau"

source

pub fn is_readonly(&self) -> bool

Available on crate feature luau only.

Returns readonly attribute of the table.

Requires feature = "luau"

source

pub fn to_pointer(&self) -> *const c_void

Converts this table to a generic C pointer.

Different tables will give different pointers. There is no way to convert the pointer back to its original value.

Typically this function is used only for hashing and debug information.

source

pub fn into_owned(self) -> OwnedTable

Available on crate feature unstable and non-crate feature send only.

Convert this handle to owned version.

source

pub fn pairs<K: FromLua<'lua>, V: FromLua<'lua>>(self) -> TablePairs<'lua, K, V>

Consume this table and return an iterator over the pairs of the table.

This works like the Lua pairs function, but does not invoke the __pairs metamethod.

The pairs are wrapped in a Result, since they are lazily converted to K and V types.

§Note

While this method consumes the Table object, it can not prevent code from mutating the table while the iteration is in progress. Refer to the Lua manual for information about the consequences of such mutation.

§Examples

Iterate over all globals:

let globals = lua.globals();

for pair in globals.pairs::<Value, Value>() {
    let (key, value) = pair?;
    // ...
}
source

pub fn for_each<K, V>(&self, f: impl FnMut(K, V) -> Result<()>) -> Result<()>
where K: FromLua<'lua>, V: FromLua<'lua>,

Iterates over the pairs of the table, invoking the given closure on each pair.

This method is similar to Table::pairs, but optimized for performance. It does not invoke the __pairs metamethod.

source

pub fn sequence_values<V: FromLua<'lua>>(self) -> TableSequence<'lua, V>

Consume this table and return an iterator over all values in the sequence part of the table.

The iterator will yield all values t[1], t[2] and so on, until a nil value is encountered. This mirrors the behavior of Lua’s ipairs function but does not invoke any metamethods.

§Note

While this method consumes the Table object, it can not prevent code from mutating the table while the iteration is in progress. Refer to the Lua manual for information about the consequences of such mutation.

§Examples
let my_table: Table = lua.load(r#"
    {
        [1] = 4,
        [2] = 5,
        [4] = 7,
        key = 2
    }
"#).eval()?;

let expected = [4, 5];
for (&expected, got) in expected.iter().zip(my_table.sequence_values::<u32>()) {
    assert_eq!(expected, got?);
}

Trait Implementations§

source§

impl<'lua> AsRef<Table<'lua>> for Table<'lua>

source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<'lua> Clone for Table<'lua>

source§

fn clone(&self) -> Table<'lua>

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
source§

impl Debug for Table<'_>

source§

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

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

impl<'lua> FromLua<'lua> for Table<'lua>

source§

fn from_lua(value: Value<'lua>, _: &'lua Lua) -> Result<Table<'lua>>

Performs the conversion.
source§

impl<'lua> IntoLua<'lua> for &Table<'lua>

source§

fn into_lua(self, _: &'lua Lua) -> Result<Value<'lua>>

Performs the conversion.
source§

impl<'lua> IntoLua<'lua> for Table<'lua>

source§

fn into_lua(self, _: &'lua Lua) -> Result<Value<'lua>>

Performs the conversion.
source§

impl<'lua, T> PartialEq<&[T]> for Table<'lua>
where T: IntoLua<'lua> + Clone,

source§

fn eq(&self, other: &&[T]) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'lua, T> PartialEq<[T]> for Table<'lua>
where T: IntoLua<'lua> + Clone,

source§

fn eq(&self, other: &[T]) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'lua, T, const N: usize> PartialEq<[T; N]> for Table<'lua>
where T: IntoLua<'lua> + Clone,

source§

fn eq(&self, other: &[T; N]) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'lua> PartialEq for Table<'lua>

source§

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

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'lua> Serialize for Table<'lua>

source§

fn serialize<S: Serializer>(&self, serializer: S) -> StdResult<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
source§

impl<'lua> TableExt<'lua> for Table<'lua>

source§

fn call<A, R>(&self, args: A) -> Result<R>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua>,

Calls the table as function assuming it has __call metamethod. Read more
source§

fn call_async<A, R>(&self, args: A) -> LocalBoxFuture<'lua, Result<R>>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua> + 'lua,

Available on crate feature async only.
Asynchronously calls the table as function assuming it has __call metamethod. Read more
source§

fn call_method<A, R>(&self, name: &str, args: A) -> Result<R>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua>,

Gets the function associated to key from the table and executes it, passing the table itself along with args as function arguments. Read more
source§

fn call_function<A, R>(&self, name: &str, args: A) -> Result<R>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua>,

Gets the function associated to key from the table and executes it, passing args as function arguments. Read more
source§

fn call_async_method<A, R>( &self, name: &str, args: A ) -> LocalBoxFuture<'lua, Result<R>>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua> + 'lua,

Available on crate feature async only.
Gets the function associated to key from the table and asynchronously executes it, passing the table itself along with args as function arguments and returning Future. Read more
source§

fn call_async_function<A, R>( &self, name: &str, args: A ) -> LocalBoxFuture<'lua, Result<R>>
where A: IntoLuaMulti<'lua>, R: FromLuaMulti<'lua> + 'lua,

Available on crate feature async only.
Gets the function associated to key from the table and asynchronously executes it, passing args as function arguments and returning Future. Read more

Auto Trait Implementations§

§

impl<'lua> Freeze for Table<'lua>

§

impl<'lua> !RefUnwindSafe for Table<'lua>

§

impl<'lua> !Send for Table<'lua>

§

impl<'lua> !Sync for Table<'lua>

§

impl<'lua> Unpin for Table<'lua>

§

impl<'lua> !UnwindSafe for Table<'lua>

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<'lua, T> FromLuaMulti<'lua> for T
where T: FromLua<'lua>,

source§

fn from_lua_multi(values: MultiValue<'lua>, lua: &'lua Lua) -> Result<T, Error>

Performs the conversion. Read more
source§

fn from_lua_args( args: MultiValue<'lua>, i: usize, to: Option<&str>, lua: &'lua Lua ) -> Result<T, Error>

source§

unsafe fn from_stack_multi(nvals: i32, lua: &'lua Lua) -> Result<T, Error>

source§

unsafe fn from_stack_args( nargs: i32, i: usize, to: Option<&str>, lua: &'lua Lua ) -> Result<T, Error>

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<'lua, T> IntoLuaMulti<'lua> for T
where T: IntoLua<'lua>,

source§

fn into_lua_multi(self, lua: &'lua Lua) -> Result<MultiValue<'lua>, Error>

Performs the conversion.
source§

unsafe fn push_into_stack_multi(self, lua: &'lua Lua) -> Result<i32, Error>

source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer ) -> Result<(), ErrorImpl>

source§

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

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

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

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

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

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

§

type Error = Infallible

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

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

Performs the conversion.
source§

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

§

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.