Lua Programming/How to Lua/table

From Wikibooks, open books for an open world
< Lua Programming‎ | How to Lua
Jump to: navigation, search

A table is an aggregate datatype that can be used for storing collections containing other objects.

Creating a table[edit]

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[edit]

It is possible for an empty table to be defined:

mytable = {}    -- Create an empty table

Outputting the contents of a table[edit]

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[edit]

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[edit]

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[edit]

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