← Back to Lua Course | Chapter 6: OOP with Metatables | Lesson 6 of 7

Operator metamethods

Metamethods like __add, __eq and __tostring let your objects work with operators and print.

In this page:

  1. Operator metamethods

Operator metamethods

Arithmetic operators map to __add, __sub, __mul, __div, __mod, __pow, __unm and __idiv, and comparisons to __eq, __lt and __le. __tostring controls how tostring and print show the object, and __concat handles the .. operator. Lua tries the left operand's metamethod first and then the right one.

Note: __eq only runs when both operands are tables and are not already the same object.

Example: Operator metamethods

lua
local V = {}
V.__index = V
local function vec(x, y) return setmetatable({x = x, y = y}, V) end
V.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
V.__eq = function(a, b) return a.x == b.x and a.y == b.y end
V.__lt = function(a, b) return a.x < b.x end
V.__tostring = function(v) return "(" .. v.x .. ", " .. v.y .. ")" end
V.__concat = function(a, b) return tostring(a) .. tostring(b) end

local p, q = vec(1, 2), vec(3, 4)
print(p + q)
print(p == vec(1, 2), p < q, p > q)
print(p .. q)

-- Output:
-- (4, 6)
-- true	true	false
-- (1, 2)(3, 4)
Common Mistakes
  1. Forgetting to return a new object from __add
  2. Expecting __eq to be called when comparing with a number
  3. Not defining __tostring and printing an address
Chapter Summary
  • __add and friends overload arithmetic
  • __eq __lt __le overload comparison
  • __tostring customises print
  • The left operand is tried first
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.