Tables
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=1print(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
- freeze()
- Makes a given table read-only.
- insert()
- Inserts an element to an existing table at a specified index.
- sort()
- Sorts a given table.
- unpack()
- Takes a table and returns the elements of that table as separate values.
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.