Tables
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=1print(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.
Contribute to Docs
- 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.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours