Lua: Tables — The Only Data Structure
What you will learn
Tables are Lua's single and universal data structure — they serve as arrays, dictionaries, objects, and more.
Tables as arrays (1-indexed!)
local fruits = {"apple", "banana", "cherry"}
print(fruits[1]) -- apple (1-based indexing!)
print(#fruits) -- 3 (length operator)
table.insert(fruits, "date") -- append
table.remove(fruits, 1) -- remove first element
Important: Lua arrays are 1-indexed, not 0-indexed. fruits[0] returns nil.
Tables as dictionaries
local user = {
name = "Alice",
age = 25,
["email"] = "[email protected]" -- bracket syntax also works
}
print(user.name) -- Alice (dot notation)
print(user["name"]) -- Alice (bracket notation)
user.active = true -- add new field
user.age = nil -- remove a field (set to nil)
Both .name and ["name"] access fields. Use brackets when the key is stored in a variable or contains spaces.
Tables as objects (with metatables)
local person = { name = "Alice" }
function person:greet()
print("Hi, I'm " .. self.name)
end
person:greet() -- Hi, I'm Alice
The : syntax automatically passes self as the first argument.
Common mistakes
- Using 0-based indexing — Lua starts at 1.
- Setting a table field to
nilto remove it — this is correct, but note that nil also marks the end of array sequences for#. - Using
#on a table with gaps (nil values in the array) —#is unreliable for tables with holes. - Forgetting that tables are reference types: assignment
t2 = t1copies the reference, not the data.
Quick check below!