Lua by Example: Tables
Tables are the only data structuring mechanism in Lua. This example shows how to use them as arrays, dictionaries, and objects.
Code
-- Array-like table (1-based indexing)
local colors = {"red", "green", "blue"}
print(colors[1]) -- red
-- Dictionary-like table
local user = {
name = "Alice",
age = 30,
["favorite color"] = "blue"
}
print(user.name)
print(user["favorite color"])
-- Nested tables
local polygon = {
color = "blue",
vertices = {
{x=0, y=0},
{x=10, y=0},
{x=5, y=10}
}
}
-- Iterating
for key, value in pairs(user) do
print(key, value)
endExplanation
Tables are the heart of Lua. They are the only composite data structure in the language, but they are incredibly flexible. A table can act as an array, a dictionary (hash map), a set, a record, a graph, or even a class/object. Tables are created using curly braces {}.
When used as an array, Lua tables are conventionally 1-indexed, meaning the first element is at index 1, not 0. This can be surprising for developers coming from C-style languages. You can mix integer keys and string keys in the same table, as tables are essentially associative arrays mapping keys to values.
Accessing fields can be done using dot notation user.name (syntactic sugar for user["name"]) or bracket notation. The pairs() function is used to iterate over all key-value pairs in a table, while ipairs() is used specifically for iterating over numeric indices in order, stopping at the first nil value.
Code Breakdown
{"red", ...} creates a list. Lua automatically assigns integer keys starting from 1.pairs(user) returns an iterator function to traverse the table. The order of iteration is not guaranteed for non-numeric keys.
