0Pricing
Lua Academy · Lesson

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_1

setmetatable 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 metatable

All lessons in this course

  1. Introduction to Metatables
  2. __index and __newindex
  3. Arithmetic Metamethods
  4. __tostring and __len
← Back to Lua Academy