Tables are the only built-in data structure available in Lua. This is either elegant simplicity or confusing, depending on how you look at it.
A Lua table is a collection of key-value pairs where the keys are unique and neither the key nor the value is nil
. As such, a Lua table can resemble a dictionary, hashmap or associative array from other languages. Many structural patterns can be built with tables: stacks, queues, sets, lists, graphs, etc. Finally, tables can be used to build classes in Lua and to create a module system.
Lua does not enforce any particular rules on how tables are used. The items contained in a table can be a mixture of Lua types. So, for example, one table could contain strings, functions, booleans, numbers, and even other tables as values or keys.
A Lua table with consecutive positive integer keys beginning with 1 is said to have a sequence. The key-value pairs with positive integer keys are the elements of the sequence. Other languages call this a 1-based array. Certain standard operations and functions only work on the sequence of a table and some have non-deterministic behavior when applied to a table without a sequence.
Setting a value in a table to nil
removes it from the table. Iterators would no longer see the related key. When coding for a table with a sequence, it is important to avoid breaking the sequence; Only remove the last element or use a function, like the standard table.remove
, that shifts elements down to close the gap.