0Pricing
Lua Academy · Lesson

Arithmetic Metamethods

Overload +, -, *, / and other operators with metamethods.

Metamethod Names

Lua defines metamethods for all arithmetic operators. When Lua sees an arithmetic operation on a table, it looks for the corresponding metamethod in the table's metatable. If both operands are tables, Lua checks the left operand's metatable first.

-- Operator -> Metamethod
-- a + b    -> __add
-- a - b    -> __sub
-- a * b    -> __mul
-- a / b    -> __div
-- a % b    -> __mod
-- a ^ b    -> __pow
-- a // b   -> __idiv
-- -a       -> __unm (unary minus)
-- #a       -> __len
print("Metamethods defined for all Lua operators")

__add for Vector Addition

Define __add on a vector table to support +. The metamethod receives two operands and returns a new value. Both operands might be tables or one might be a number — your metamethod should handle both cases.

local Vec = {}
Vec.__index = Vec

Vec.__add = function(a, b)
  return setmetatable({x=a.x+b.x, y=a.y+b.y}, Vec)
end

Vec.__tostring = function(v)
  return string.format("Vec(%g,%g)", v.x, v.y)
end

function Vec.new(x,y) return setmetatable({x=x,y=y},Vec) end

local v1 = Vec.new(1,2)
local v2 = Vec.new(3,4)
print(tostring(v1 + v2))   -- Vec(4,6)

All lessons in this course

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