Tables

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 = {}
print(type(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"}
print(week[2])

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"
print(week.LastDay)

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
print(days.LastDay)

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

bald.health = 100
kate.health = 25

print(characters.Baldspot.health, characters.Kate.health)

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

print(characters.Baldspot.weapons[2])

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

Summary

  • 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