Introduction to Metatables
Set and get metatables with setmetatable/getmetatable.
What is a Metatable?
A metatable is a regular Lua table that controls the behavior of another table. When Lua encounters an operation it can't perform on a table (like arithmetic or indexing a missing key), it looks for a corresponding metamethod in the metatable. This is Lua's extension mechanism for operator overloading and OOP.
local t = {}
local mt = {__index = function(_, k) return "default_" .. k end}
setmetatable(t, mt)
print(t.foo) -- default_foo
print(t.bar) -- default_bar
print(t[1]) -- default_1setmetatable and getmetatable
setmetatable(t, mt) sets the metatable of t to mt and returns t. getmetatable(t) returns the metatable, or nil if none. You can protect a metatable from being changed by setting mt.__metatable = "protected".
local t = {x = 10}
local mt = {}
setmetatable(t, mt)
print(getmetatable(t) == mt) -- true
-- Protect metatable
mt.__metatable = "locked"
print(getmetatable(t)) -- locked
-- setmetatable(t, {}) -- ERROR: cannot change protected metatableAll lessons in this course
- Introduction to Metatables
- __index and __newindex
- Arithmetic Metamethods
- __tostring and __len