Metatables
A metatable is a table of special rules that changes how another table behaves.
In this page:
Metatables
Every table can have a metatable, set with setmetatable(t, mt) and read with getmetatable(t). The metatable holds metamethods, fields whose names start with two underscores, such as __index and __add. Lua looks them up when an operation is not defined for the table. setmetatable returns its first argument, so it can be used in an expression.
Note:
Strings share a metatable whose __index is the string table, which is why s:upper() works.
Example: Metatables
local t = {}
print(getmetatable(t))
local mt = {}
local same = setmetatable(t, mt)
print(same == t, getmetatable(t) == mt)
print(getmetatable("abc").__index == string)
-- Output:
-- nil
-- true true
-- true
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that setmetatable returns the table
- Putting metamethod names in the table itself instead of its metatable
- Assuming plain tables have metatables by default
Chapter Summary
- setmetatable attaches a metatable
- getmetatable reads it
- Metamethods start with __
- Plain tables have no metatable
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: