Lua Metatables
Every table can have a metatable: a second, ordinary table that changes how the first one behaves. When Lua hits an operation that a table doesn't support on its own (adding it with +, reading a missing key, calling it like a function), it looks in the metatable for a special field called a metamethod, such as __add or __index.
local mt = {}
local t = setmetatable({}, mt) -- setmetatable returns its first argument
print(getmetatable(t) == mt)
print(getmetatable({})) -- plain tables have no metatable
print(getmetatable("text").__index == string)true
nil
true
The last line shows why ("text"):upper() works: all strings share a metatable whose __index is the string table.
__index: defaults for missing keys
When you read a key that is not present in a table, Lua checks the metatable's __index. If it is a table, the key is looked up there:
local defaults = { colour = "grey", size = "M", stock = 0 }
local shirt = setmetatable({ colour = "navy" }, { __index = defaults })
print(shirt.colour) -- found in shirt itself
print(shirt.size) -- missing: taken from defaults
print(shirt.price) -- missing in both: nil
print(rawget(shirt, "size")) -- rawget skips the metatablenavy
M
nil
nil
__index can also be a function (table, key), called for every missing key:
local squares = setmetatable({}, {
__index = function(t, n)
local value = n * n
rawset(t, n, value) -- cache it for next time
return value
end,
})
print(squares[7], squares[12])
print(rawget(squares, 7)) -- now really stored49 144
49
__newindex: controlling assignments
__newindex runs when you assign to a key that is not already present. Use it to validate, log or redirect writes:
local function strictRecord(fields)
local allowed = {}
for _, f in ipairs(fields) do allowed[f] = true end
return setmetatable({}, {
__newindex = function(t, key, value)
if not allowed[key] then
error("unknown field '" .. tostring(key) .. "'", 2)
end
rawset(t, key, value)
end,
})
end
local user = strictRecord({ "name", "email" })
user.name = "Lena"
print(user.name)
print(pcall(function() user.nmae = "typo" end))Lena
false /app/output.s:17: unknown field 'nmae'
rawset stores the value without triggering __newindex again (which would loop forever). Level 2 in error blames the line that made the assignment rather than the metamethod.
Read-only tables
Combining an empty proxy with __index and __newindex gives a table that can be read but not changed:
local function readOnly(t)
return setmetatable({}, {
__index = t,
__newindex = function() error("attempt to modify a read-only table", 2) end,
__len = function() return #t end,
})
end
local DAYS = readOnly({ "Mon", "Tue", "Wed", "Thu", "Fri" })
print(DAYS[2], #DAYS)
local ok, err = pcall(function() DAYS[1] = "Sun" end)
print(ok, err)Tue 5
false /app/output.s:11: attempt to modify a read-only table
The raw functions
| Function | Does the same as … but ignores metamethods |
|---|---|
rawget(t, k) |
t[k] |
rawset(t, k, v) |
t[k] = v |
rawequal(a, b) |
a == b |
rawlen(t) |
#t |
Protecting a metatable
If the metatable has a __metatable field, getmetatable returns that value instead, and setmetatable refuses to change it. Libraries use this to stop users from tampering with their objects:
local obj = setmetatable({}, { __metatable = "locked" })
print(getmetatable(obj))
print(pcall(setmetatable, obj, {}))locked
false cannot change a protected metatable
Test yourself
When is a table's __index metamethod used?
- On every read
- When reading a key that is absent from the table
- When writing any key
- When the table is printed
Why use rawset inside a __newindex function?
- It is faster than
= - To store the value without triggering
__newindexagain - To make the field read-only
- It is required by the syntax
What does setmetatable(t, mt) return?
mtttrue- Nothing