Lua Programming/How to Lua/table
A table is an aggregate datatype that can be used for storing collections containing other objects.
Creating a table
A table can be defined by a comma separated list of values enclosed in a pair of squiggly braces
mytable = { "apple" , "banana", "cherry" }
Creating an empty table
It is possible for an empty table to be defined:
mytable = {} -- Create an empty table
Outputting the contents of a table
If an attempt is made to output the value of a table using a print statement, then a unique indicator is output that indicates the table datatype, and the address of the table:
print (mytable)
Referencing table elements
The elements of a table can be referenced using either an integer element number or using a hashkey.
The box brackets can be used to reference table elements:
Data structures
In lua, data structures are implemented using tables. Note that a comma is used to separate the structure elements:
student = {
name = "Bob",
age = 19
}
print (student.name)
print (student.age)
-- Alternative referencing syntax
print (student["name"])
print (student["age"])
Using a table as an array
By using numeric hashkey values, it is possible for a table to be used as an array:
fruits = { "apple", "banana", "cherry" }
print (fruits[2]) -- The second element is a banana
Last modified on 1 March 2011, at 17:13