Tables

AngelAv1's avatar
Published Aug 23, 2023Updated Jul 26, 2024
Contribute to Docs

In Lua, tables are associative Arrays. Values that are stored in a table can be referenced with numbers and keys.

Syntax

Table objects are created using a constructor expression, in this case, a pair of curly braces:

t = {}

To initialize a table with predefined elements, insert values inside the curly braces and separated with commas:

t = {"element1", "element2", "element3"}

To initialize values with assigned keys, define the keys using square brackets and an equal sign =:

t = {["key1"] = "element1",
["key2"] = "element2",
["key2"] = "element3"}

To add values later in code, use square brackets again to set the key that’s associated with the value:

t[mykey] = myvalue

Any data type other than nil can be used as a key.

After creating a table with a key-value pair(s), values are indexed through the associated keys using square brackets:

t = {}
t["a"] = 1 -- New table entry where key="a" and value=1
print(t["a"])

Output for the above code is:

1

Values can also be accessed using dot notation:

print(t.a)

Output for the above code is:

1

If no key was defined, use a numeric index:

t = {"a", "b", "c"}
print(t[1])

Output for the above code is:

a
letters = {"a", "b", "c'}
print(letters[3])

Output for the above code is:

c

Table Functions

The table library is built-in and will automatically work when referencing the global keyword, table. Below is the list of the available Table functions:

Tables

.remove()
Removes and returns the element at a specified position from a table (array).
concat()
Joins table elements into a string.
insert()
Inserts an element to an existing table at a specified index.
move()
Copies elements from one table to another.
pack()
Returns a table comprised of the multiple values passed to it.
sort()
Sorts a given table.
unpack()
Takes a table and returns the elements of that table as separate values.

All contributors

Contribute to Docs

Learn Lua on Codecademy