Lua Tables and Metatables: The Building Blocks
Everything in Lua is built on tables. Understanding metatables unlocks operator overloading and inheritance.
Key Insights
- Tables are Lua’s only data structure — they serve as arrays, dicts, objects, and modules
- Metatables define behavior for operations like +, ==, and indexing
- Prototype-based OOP is achieved through __index metamethod chaining
Tables as Everything
-- Array
local fruits = {"apple", "banana", "cherry"}
-- Dictionary
local config = {host = "localhost", port = 8080}
-- Mixed
local data = {1, 2, 3, name = "test", [99] = true}
Metatables for Operator Overloading
local Vector = {}
Vector.__index = Vector
function Vector.new(x, y)
return setmetatable({x = x, y = y}, Vector)
end
function Vector.__add(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
local v = Vector.new(1, 2) + Vector.new(3, 4) -- {x=4, y=6}
Inheritance via __index
local Animal = {}
Animal.__index = Animal
function Animal:speak() return "..." end
local Dog = setmetatable({}, {__index = Animal})
Dog.__index = Dog
function Dog:speak() return "Woof!" end