From PZwiki
Jump to: navigation, search
Language policy Language: [[::Tables|English]]

Tables is the last datatype to be introduced in these tutorials. In Lua they are very flexible and extremely useful. They are basically lists of values held in one place. To create one, we use a table constructor, represented by curly brackets, like so:

week = {}

This creates a table called 'week'. We can now start adding values into the table. There are multiple ways of doing this. Tables that are arrays, i.e. tables with the indexes being numbers, we can simply write as so:

week = {"Monday", "Tuesday", "Wednesday"}

Table fields can be understood is terms of table[key] = value
The above is the equivalent of writing:

week = {[1] = "Monday", [2] = "Tuesday", [3] = "Wednesday"}

We can also specify individual positions:

week[4] = "Thursday"
week[5] = "Friday"

The other type of table is called an associative table (also known as an associative array) - this is one where we use other datatypes for indexes instead of numbers, or the array has obvious gaps. With these types of tables you can add new fields using only a dot:

week = {}
week.LastDay = "Sunday"

Note that tables are always anonymous - there is no fixed relationship between the variable pointing to the table and the table itself:

week = {}
week.LastDay = "Sunday"

days = week

Also note that that week.x is not the same as week[x]. week.x is a field indexed by "x", while week[x] is a field indexed by the variable x. Tables can contain any datatype, including tables:

characters = {Baldspot  = {}, Kate = {} }
bald = characters.Baldspot
kate = characters.Kate = 100 = 25


bald.weapons = {"Knife", "Frying Pan", "Baseball Bat"}


Tables can also include functions. These functions can actually affect the table contents itself, but this will be covered in a later OOP tutorial.


  • Tables are created using the table constructor, {}
  • Arrays are tables with logical numerical indexes
  • Associative tables are tables with indexes that are not numbers
  • Tables can contain any datatype