Tables


Lua implements a single data structure, which is implemented as a general-purpose collection that encompasses functionality that is usually implemented by several different data structures in other programming languages. This makes tables powerful, but can also make it a bit challenging to work with, and can lead to surprising results if one is not careful. For example, while tables can act as both lists and mappings, most table functions generally make an assumption about how the table is being used. When a table function is used in the wrong context it won't generate an error, it will just return an unexpected result.

We find it helpful to think of the table as a Swiss Army Knife; it can support many functions, but in order to complete a task you have to first determine the role you want the knife to perform, then use the knife in a way that is consistent with that role.

For example, if the goal is to open a bottle, then the knife plays the role of a bottle opener. The bottle-opener tool must be selected, and the knife must be used like a bottle-opener. It would be difficult to open a bottle with the toothpick or magnifying glass tools, even if they are used like a bottle-opener. Likewise, it would be equally difficult to open a bottle with the bottle-opener tool if it were to be used like a toothpick or a magnifying glass.

With this in mind, rather than discuss tables as a single, all-encompassing data structure, we will identify the role that we want the table to perform, then discuss how to use the tables in that role.

Of the many different roles a table can perform, we currently focus on the most common: