TExcelTAD
Home › Lua › Lua Metamethods

Lua Metamethods

Metamethods let your tables work with Lua's operators and built-in functions. Define __add and you can write a + b; define __tostring and print shows something readable. This lesson builds a small 2D vector type to show the most useful ones.

Metamethod Triggered by
__add, __sub, __mul, __div, __mod, __pow, __unm, __idiv + - * / % ^, unary -, //
__band, __bor, __bxor, __shl, __shr, __bnot bitwise operators
__concat ..
__eq, __lt, __le ==, < (and >), <= (and >=)
__len #
__index, __newindex reading a missing key, assigning a new key
__call calling the table like a function
__tostring tostring() and therefore print
__name the type name shown in some error messages
__close a <close> variable going out of scope
__gc, __mode garbage collection (see the weak tables lesson)

Arithmetic and __tostring

lua · try it yourself
local Vec = {}
Vec.__index = Vec

local function vec(x, y) return setmetatable({ x = x, y = y }, Vec) end

Vec.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
Vec.__sub = function(a, b) return vec(a.x - b.x, a.y - b.y) end
Vec.__unm = function(a) return vec(-a.x, -a.y) end
Vec.__mul = function(a, b)
  if type(a) == "number" then return vec(a * b.x, a * b.y) end
  if type(b) == "number" then return vec(a.x * b, a.y * b) end
  return a.x * b.x + a.y * b.y     -- vector * vector: dot product
end
Vec.__tostring = function(v) return "(" .. v.x .. ", " .. v.y .. ")" end

local a, b = vec(1, 2), vec(3, 4)
print(a + b, b - a, -a)
print(a * 3, 2 * b, a * b)
(4, 6)	(2, 2)	(-1, -2)
(3, 6)	(6, 8)	11

For a binary operator, Lua checks the left operand's metatable first, then the right one's. That's why 2 * b works: the number has no __mul, so Lua uses b's.

Comparison: __eq, __lt, __le

Without __eq, two tables are equal only if they are the same object. __lt and __le enable <, >, <= and >= (Lua swaps the operands for > and >=):

lua · try it yourself
local Money = {}
Money.__index = Money
local function money(cents) return setmetatable({ cents = cents }, Money) end

Money.__eq = function(a, b) return a.cents == b.cents end
Money.__lt = function(a, b) return a.cents < b.cents end
Money.__le = function(a, b) return a.cents <= b.cents end
Money.__tostring = function(m) return string.format("$%.2f", m.cents / 100) end

local price, budget = money(1999), money(2500)
print(price == money(1999), price ~= budget)
print(price < budget, price > budget, budget >= money(2500))

local list = { money(500), money(120), money(990) }
table.sort(list)                 -- uses __lt
for _, m in ipairs(list) do io.write(tostring(m), " ") end
print()
true	true
true	false	true
$1.20 $5.00 $9.90 

__len, __concat and __call

lua · try it yourself
local Playlist = {}
Playlist.__index = Playlist

local function playlist(...) return setmetatable({ songs = { ... } }, Playlist) end

Playlist.__len = function(p) return #p.songs end
Playlist.__concat = function(a, b)
  local merged = playlist(table.unpack(a.songs))
  for _, s in ipairs(b.songs) do merged.songs[#merged.songs + 1] = s end
  return merged
end
Playlist.__call = function(p, i) return p.songs[i] end   -- p(i)
Playlist.__tostring = function(p) return "[" .. table.concat(p.songs, ", ") .. "]" end

local rock = playlist("Paranoid", "Hysteria")
local jazz = playlist("So What")
local mix = rock .. jazz

print(#rock, #mix)
print(mix)
print(mix(3))
2	3
[Paranoid, Hysteria, So What]
So What

__call receives the table itself as the first argument, followed by the call's arguments.

__index for methods

Setting Vec.__index = Vec (as above) means any key missing from an instance is looked up in Vec. That is how methods are shared between objects, and it is the basis of the next lesson:

lua · try it yourself
local Vec = {}
Vec.__index = Vec
function Vec.new(x, y) return setmetatable({ x = x, y = y }, Vec) end
function Vec.length(v) return math.sqrt(v.x ^ 2 + v.y ^ 2) end

local v = Vec.new(3, 4)
print(v.length(v), v:length())     -- v:length() is sugar for v.length(v)
print(rawget(v, "length"))         -- not stored in v itself
5.0	5.0
nil

Test yourself

Which metamethod makes print(obj) show a custom text?

  1. __print
  2. __string
  3. __tostring
  4. __name

For 5 + v, where v is a table with __add, which metatable does Lua use?

  1. None: it is an error
  2. v's, because the number has none
  3. The number's only
  4. _G's

Which metamethod lets you call a table like a function, t(1, 2)?

  1. __invoke
  2. __call
  3. __func
  4. __index