Tables

Published Aug 23, 2023
Contribute to Docs

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

Creating Tables

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

t = {}

To add values to the table, use square brackets 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.

Accessing Table Values

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: 1

Values can also be accessed using dot notation:

print(t.a) -- Output: 1

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

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.
remove()
Removes a value from a table.
sort()
Sorts a given table.
unpack()
Takes a table and returns the elements of that table as separate values.

All contributors

Looking to contribute?

Learn Lua on Codecademy