Tables implement associative arrays. That is, arrays of key/value pairs.
The table constructor can also add initial key/value pairs to the table, eg.
You can add elements later or in the constructor. Ultimately either method gives the same end result.
Once you have a table you can get at the values in it by "indexing" into the table. One way is this:
Or in the case of string keys, where the key follows the rules for identifiers, you can use this shortcut:
Tables are anonymous, they don't have to be stored in any variable, or one table might be stored (by reference) in many variables. For example:
That table existed even though it was not assigned to a variable.
In this example both x and y refer to the same table. The assignment did not make a copy of the table, it made a copy of the reference to the table.
Table constructors in the general form provide the key in brackets:
This is equivalent to the earlier example.
For other data types you must use brackets for the key, eg.
Both the keys and values can be any type except nil, so a table can contain nested tables, or boolean values, for example.
Lua can also automatically assign keys starting at one, like this:
Elements in tables are separated by a comma or semicolon. It is acceptable to have a trailing comma or semicolon, to assist in machine-generated tables.
Note that there is a difference between the key "10" (a string) and the key 10 (a number).
By convention, in Lua tables start with one (not zero as in C). The Lua libraries are designed around this convention. You can "manually" put an element at position 0 if you need to:
You can add elements to a table at any time, eg.
You can remove elements by assigning nil as their value, eg.
You can also use table.insert to add numerically keyed items to a table. This will shuffle existing keys upwards to make room if required.
Likewise, you can use table.remove to remove numerically keyed items from a table. This will shuffle existing keys downwards where required.
You do not specifically delete tables. Once there are no references to the table the garbage-collector will delete it. One way of encouraging that to happen is to assign nil to any variables which refer to the table:
You can see if a table is empty or not by using the next function:
See Also ...
Lua base functions
(Help topic: lua=tables)
Enter a search string to find matching documentation.
Information and images on this site are licensed under the Creative Commons Attribution 3.0 Australia License unless stated otherwise.
Gammon Software support
Forum RSS feed ( https://gammon.com.au/rss/forum.xml )