Skip to main content

table

Struct table 

Source
pub struct table;
Expand description

The type of associative arrays — the sole data-structuring mechanism in Lua.

Tables can be indexed with any value except nil and NaN, and can hold values of any type. They are used to represent arrays, sequences, records, sets, modules and objects alike. Like functions, tables are objects: variables hold references to tables, and assignment, parameter passing and returns never cause copies.

local point = { x = 10, y = 20 }
local list  = { "a", "b", "c" }
print(point.x, list[2], #list)  --> 10   b   3

Most functions in the table library assume the table is a sequence: its positive numeric keys form the set 1..#t without holes.

Implementations§

Source§

impl table

§Method form

These functions operate on a table passed as their first argument (self in the signatures). Unlike strings, plain tables have no default metatable, so the usual call is table.insert(t, v); the method form t:insert(v) only works if you point a table’s __index at the table library yourself.

Source

pub fn concat( &self, sep: option<string>, i: option<number>, j: option<number>, ) -> string

Joins the elements of a sequence into a string.

§Parameters
  • sep: a string placed between elements (default: the empty string).
  • i: index of the first element (default 1).
  • j: index of the last element (default #list).
§Return value

The string list[i] .. sep .. list[i+1] .. sep .. ... .. sep .. list[j]. All elements in the range must be strings or numbers. If i is greater than j, the empty string.

§Examples
print(table.concat({"a", "b", "c"}))          --> abc
print(table.concat({"a", "b", "c"}, ", "))    --> a, b, c
print(table.concat({1, 2, 3}, "+", 2, 3))     --> 2+3
Source

pub fn insert(&self, pos: option<number>, value: any)

Inserts an element into a sequence.

§Parameters
  • pos: the position for the new element, from 1 to #list + 1 (default #list + 1, i.e. append).
  • value: the value to insert.
§Description

Inserts value at position pos, shifting up the elements list[pos], list[pos+1], ..., list[#list]. The two-argument form appends value at the end of the sequence.

§Examples
local t = {"a", "c"}
table.insert(t, "d")        -- {"a", "c", "d"}
table.insert(t, 2, "b")     -- {"a", "b", "c", "d"}
print(table.concat(t))      --> abcd
§See also

remove

Source

pub fn remove(&self, pos: option<number>) -> any

Removes an element from a sequence.

§Parameters
  • pos: the position of the element to remove (default #list, i.e. the last element).
§Return value

The removed value. The elements list[pos+1], ..., list[#list] are shifted down to close the gap.

§Examples
local t = {"a", "b", "c"}
print(table.remove(t))        --> c
print(table.remove(t, 1))     --> a
print(table.concat(t))        --> b
§See also

insert

Source

pub fn sort(&self, comp: option<function>)

Sorts a sequence in place.

§Parameters
  • comp: a function that receives two list elements and returns true when the first must come before the second in the final order. When absent, the standard < operator is used. comp must define a strict order: comp(a, a) must be false.
§Description

Sorts the elements from list[1] to list[#list] in place. The sort algorithm is not stable: elements considered equal by the given order may have their relative positions changed by the sort.

§Examples
local t = {3, 1, 2}
table.sort(t)
print(table.concat(t, ","))    --> 1,2,3
table.sort(t, function(a, b) return a > b end)
print(table.concat(t, ","))    --> 3,2,1
Source

pub fn unpack(&self, i: option<number>, j: option<number>) -> Repeatable<any>

Returns the elements of a sequence as multiple values.

§Parameters
  • i: index of the first element (default 1).
  • j: index of the last element (default #list).
§Return value

The values list[i], list[i+1], ..., list[j].

§Examples
print(table.unpack({"a", "b", "c"}))       --> a   b   c
print(table.unpack({"a", "b", "c"}, 2))    --> b   c
local function sum3(x, y, z) return x + y + z end
print(sum3(table.unpack({1, 2, 3})))       --> 6
§See also

pack

Source§

impl table

§Library functions

These functions do not operate on a single table self and are only reachable through the library table, e.g. table.pack(...).

Source

pub fn create(nseq: number, nrec: option<number>) -> table

Creates a preallocated table. New in Lua 5.5.

§Parameters
  • nseq: a hint for how many elements the table will have as a sequence.
  • nrec: a hint for how many other elements the table will have (default 0).
§Return value

A new empty table with memory preallocated for nseq sequence elements and nrec other elements. Preallocation avoids incremental growth and rehashing, which helps performance when the final size of the table is known in advance.

§Examples
local t = table.create(3)
t[1], t[2], t[3] = "a", "b", "c"   -- no reallocation happens
print(#t)    --> 3
§See also

pack

Source

pub fn move( a1: table, f: number, e: number, t: number, a2: option<table>, ) -> table

Moves a range of elements from one table to another.

§Parameters
  • a1: the source table.
  • f: index of the first element to move.
  • e: index of the last element to move.
  • t: the destination index.
  • a2: the destination table (default a1).
§Return value

The destination table. Performs the equivalent of the multiple assignment a2[t], ··· = a1[f], ···, a1[e]. The ranges may overlap, and the number of elements moved must fit in an integer.

§Examples
local a = {1, 2, 3, 4}
local b = table.move(a, 2, 4, 1, {})
print(table.concat(b, ","))    --> 2,3,4
table.move(a, 1, 3, 2)         -- shift right inside a
print(table.concat(a, ","))    --> 1,1,2,3
Source

pub fn pack(values: Repeatable<any>) -> table

Packs its arguments into a new table.

§Parameters
  • ···: any number of values.
§Return value

A new table with all arguments stored into keys 1, 2, etc. and with a field n holding the total number of arguments. The resulting table may not be a sequence, if some arguments are nil.

§Examples
local t = table.pack("a", "b", "c")
print(t.n, t[1], t[3])    --> 3   a   c
local u = table.pack(1, nil, 3)
print(u.n)                --> 3   (n counts the nil too)
§See also

unpack, select

Source§

impl table

§Extended library — feature extended

Sequence functions from extended.lua, inspired by Rust. All of them return new tables — only the standard library’s sort, insert and remove mutate. Signatures with self take the table as their first argument: table.map(t, f).

Source

pub fn map(&self, f: function) -> table

Available on crate feature extended only.

Transforms every element of a sequence.

Inspired by Rust’s Iterator::map.

§Parameters
  • f: called as f(value, index); its result becomes the element of the new sequence.
§Examples
print(inspect(table.map({1, 2, 3}, function(v) return v * 2 end)))
--> { 2, 4, 6 }
§See also

filter, fold

Source

pub fn filter(&self, pred: function) -> table

Available on crate feature extended only.

Keeps the elements of a sequence that satisfy a predicate.

Inspired by Rust’s Iterator::filter.

§Examples
print(inspect(table.filter({1, 2, 3, 4}, function(v)
  return v % 2 == 0
end)))
--> { 2, 4 }
§See also

map, find

Source

pub fn fold(&self, f: function, init: option<any>) -> any

Available on crate feature extended only.

Folds a sequence into a single value.

Inspired by Rust’s Iterator::fold.

§Parameters
  • f: called as f(accumulator, value).
  • init: the initial accumulator. When absent, folding starts from the first element.
§Examples
print(table.fold({1, 2, 3, 4}, function(a, b) return a + b end))
--> 10
print(table.fold({1, 2, 3}, function(a, b) return a + b end, 100))
--> 106
§See also

sum, map

Source

pub fn find(&self, pred: function) -> option<(any, number)>

Available on crate feature extended only.

Finds the first element satisfying a predicate.

Inspired by Rust’s Iterator::find.

§Return value

The first matching value and its index, or nil when nothing matches.

§Examples
print(table.find({5, 6, 7}, function(v) return v > 5 end))
--> 6   2
§See also

contains, filter

Source

pub fn contains(&self, value: any) -> boolean

Available on crate feature extended only.

Tests whether a sequence contains a value (compared with ==).

Inspired by Rust’s std::collections::HashSet::contains.

§Examples
print(table.contains({1, 2, 3}, 2))    --> true
print(table.contains({1, 2, 3}, 9))    --> false
Source

pub fn keys(&self) -> table

Available on crate feature extended only.

Returns the keys of a table as a new sequence. The order is unspecified, as with pairs.

Inspired by Rust’s std::collections::HashMap::keys.

§Examples
local ks = table.keys({ a = 1, b = 2 })
table.sort(ks)
print(inspect(ks))    --> { "a", "b" }
§See also

values

Source

pub fn values(&self) -> table

Available on crate feature extended only.

Returns the values of a table as a new sequence. The order is unspecified.

Inspired by Rust’s std::collections::HashMap::values.

§Examples
local vs = table.values({ a = 1, b = 2 })
table.sort(vs)
print(inspect(vs))    --> { 1, 2 }
§See also

keys

Source

pub fn reverse(&self) -> table

Available on crate feature extended only.

Returns a new sequence with the elements in reverse order.

Inspired by Rust’s slice::reverse.

§Examples
print(inspect(table.reverse({1, 2, 3})))    --> { 3, 2, 1 }
Source

pub fn slice(&self, i: option<number>, j: option<number>) -> table

Available on crate feature extended only.

Copies a contiguous range into a new sequence. With Lua index conventions: 1-based, inclusive, negative indices count from the end (as in string::sub).

§Examples
print(inspect(table.slice({1, 2, 3, 4, 5}, 2, 4)))    --> { 2, 3, 4 }
print(inspect(table.slice({1, 2, 3, 4, 5}, -2)))      --> { 4, 5 }
Source

pub fn zip(a: table, b: table) -> table

Available on crate feature extended only.

Pairs two sequences element by element.

Inspired by Rust’s Iterator::zip.

§Return value

A new sequence of two-element tables {a[i], b[i]}, stopping at the end of the shorter input.

§Examples
print(inspect(table.zip({1, 2, 3}, {"a", "b"})))
--> { { 1, "a" }, { 2, "b" } }
Source

pub fn any(&self, pred: option<function>) -> boolean

Available on crate feature extended only.

Tests whether any element satisfies a predicate.

Without a predicate, tests Lua truthiness. The empty sequence yields false.

Inspired by Rust’s Iterator::any.

§Examples
print(table.any({false, nil, 3}))                       --> true
print(table.any({1, 2}, function(v) return v > 1 end))  --> true
print(table.any({}))                                    --> false
§See also

all

Source

pub fn all(&self, pred: option<function>) -> boolean

Available on crate feature extended only.

Tests whether every element satisfies a predicate. Without a predicate, tests Lua truthiness. The empty sequence yields true (vacuous truth).

Inspired by Rust’s Iterator::all.

§Examples
print(table.all({1, "x", true}))                        --> true
print(table.all({2, 3}, function(v) return v > 2 end))  --> false
print(table.all({}))                                    --> true
§See also

any

Source

pub fn copy(&self, deep: option<boolean>) -> table

Available on crate feature extended only.

Copies a table.

§Parameters
  • deep: when true, copies nested tables recursively — including table keys — and follows cycles safely.
§Return value

A new table. The metatable reference is kept in both modes (the metatable itself is never copied).

§Examples
local src = {1, {2}}
local sh = table.copy(src)
print(sh[2] == src[2])    --> true    (shallow: shared inner table)
local dp = table.copy(src, true)
print(dp[2] == src[2])    --> false   (deep: its own inner table)
Source

pub fn uniq(&self) -> table

Available on crate feature extended only.

Removes duplicate values, keeping first occurrences in order.

§Examples
print(inspect(table.uniq({1, 2, 1, 3, 2})))    --> { 1, 2, 3 }
Source

pub fn sum(&self) -> number

Available on crate feature extended only.

Sums a sequence of numbers. The empty sequence sums to 0.

Inspired by Rust’s Iterator::sum.

§Examples
print(table.sum({1, 2, 3.5}))    --> 6.5
print(table.sum({}))             --> 0
§See also

fold

Trait Implementations§

Source§

impl arithmetic for table

Source§

fn __add(&self, other: any) -> any

The addition (+) operation. Read more
Source§

fn __sub(&self, other: any) -> any

The subtraction (-) operation. Read more
Source§

fn __mul(&self, other: any) -> any

The multiplication (*) operation. Read more
Source§

fn __div(&self, other: any) -> any

The division (/) operation. Read more
Source§

fn __mod(&self, other: any) -> any

The modulo (%) operation. Read more
Source§

fn __pow(&self, other: any) -> any

The exponentiation (^) operation. Read more
Source§

fn __unm(&self) -> any

The negation (unary -) operation. Read more
Source§

fn __idiv(&self, other: any) -> any

The floor division (//) operation. Read more
Source§

impl bitwise for table

Source§

fn __band(&self, other: any) -> any

The bitwise AND (&) operation. Read more
Source§

fn __bor(&self, other: any) -> any

The bitwise OR (|) operation. Read more
Source§

fn __bxor(&self, other: any) -> any

The bitwise exclusive OR (~) operation. Read more
Source§

fn __bnot(&self) -> any

The bitwise NOT (unary ~) operation. Read more
Source§

fn __shl(&self, other: any) -> any

The bitwise left shift (<<) operation. Read more
Source§

fn __shr(&self, other: any) -> any

The bitwise right shift (>>) operation. Read more
Source§

impl callable for table

Source§

fn __call(&self, args: Repeatable<any>) -> Repeatable<any>

The call operation f(args). Invoked when Lua tries to call a non-function value: its __call metavalue is called with the value itself as the first argument, followed by the original arguments. Read more
Source§

impl comparison for table

Source§

fn __eq(&self, other: any) -> boolean

The equal (==) operation. Only invoked when the values being compared are both tables or both full userdata and they are not primitively equal. The result is always converted to a boolean. Read more
Source§

fn __lt(&self, other: any) -> boolean

The less than (<) operation. Read more
Source§

fn __le(&self, other: any) -> boolean

The less equal (<=) operation. Read more
Source§

impl concatenation for table

Source§

fn __concat(&self, other: any) -> any

The concatenation (..) operation. Invoked whenever an operand is neither a string nor a number. Read more
Source§

impl indexing for table

Source§

fn __index(&self, key: any) -> any

The indexing access operation t[key]. Invoked when t is not a table or when key is not present in the table. The metavalue may be a function (called with t and key) or a table (in which the access is repeated) — the latter is the basis of inheritance in Lua. Read more
Source§

fn __newindex(&self, key: any, value: any)

The indexing assignment t[key] = value. Invoked when t is not a table or when key is not present in the table. Like __index, the metavalue may be a function or another table. Read more
Source§

impl length for table

Source§

fn __len(&self) -> number

The length (#) operation. If the value is not a string and its metatable defines __len, that metavalue is called with the value as argument and its result becomes the length. Read more
Source§

impl lifecycle for table

Source§

fn __gc(&self)

The finalizer: called by the garbage collector when the value is collected, if the metatable had a __gc field when it was set. Read more
Source§

fn __close(&self, errobj: any)

Called when the value, used as a to-be-closed variable (local x <close> = ...), goes out of scope. Read more
Source§

fn __mode(&self) -> string

A metavalue controlling how the value behaves as a weak table: "k" for weak keys, "v" for weak values, "kv" for both. Read more
Source§

fn __metatable(&self) -> any

If present, protects the metatable: getmetatable returns this metavalue instead, and setmetatable raises an error. Read more
Source§

impl tostring for table

Source§

fn __tostring(&self) -> string

Invoked by tostring() (and therefore by print) to convert the value to a string. Read more
Source§

fn __name(&self) -> string

A string naming the type of the value, used in error messages and by tostring when __tostring is absent. Read more

Auto Trait Implementations§

§

impl Freeze for table

§

impl RefUnwindSafe for table

§

impl Send for table

§

impl Sync for table

§

impl Unpin for table

§

impl UnsafeUnpin for table

§

impl UnwindSafe for table

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.