Lua Basics

Tables

The more you know Lua the more you realize how core to the language tables are. Lua tables have a dual nature of being both an array and an associative hash table. They are the basis of objects in the language. They can be used to make other data structures like linked lists and so on.

The simplest way to use and access a table is as a collection of values indexed by an integer:

myvar = {98.6, "Dr. John Smith", "Radiology"}
trace(myvar[1])         -- displays 98.6
trace(myvar[3])         -- displays "Radiology"
myvar[4] = "ABC Health" -- new entry, key 4, value "ABC Health"

Note: The first element of this table has index the 1, not 0. The values in a table can be of any type, including strings, numbers, booleans, nil, functions or other tables.

You can also specify keys to identify the values in a table:

myvar = {temperature=98.6, doctor="Dr. John Smith", department="Radiology"}
trace(myvar["temperature"])      -- displays 98.6
myvar["works_at"] = "ABC Health" -- new entry, key "works_at", value "ABC Health"

In Lua, a[“b”] and a.b are identical:

trace(myvar["temperature"]) -- displays 98.6
trace(myvar.temperature)    -- also displays 98.6

This makes it easy to implement structures or records.

Tables can contain other tables as values:

-- new entry, key "temperatures", value is a table of 3 temperatures 
myvar["temperatures"] = {morning=98.6, afternoon=100.3, evening=99.4}
trace(myvar["temperatures"]["morning"]) -- displays 98.6
trace(myvar.temperatures.morning)       -- displays 98.6

A very useful technique with tables is to be able to iterate through their keys using pairs which gives all key value pairs and ipairs which gives integer keys only:

for Key,Value in pairs(T) do
   trace(Key.." = "..Value)
end

-- or for just integer keys:

for Key,Value in ipairs(T) do
   trace(Key.." = "..Value)
end

Tables are powerful, for more detail refer to the tables section in the Lua online programming book or search for “table” and “metatable” in the online reference manual.

Tagged:

Leave A Comment?