Lesson 8 of 8 · 12 min

Metatables and objects

Every table can have a metatable: another table that changes how it behaves. Special keys called metamethods say what happens for operations like + or tostring:

local Money = {}
Money.__add = function(a, b) return setmetatable({ cents = a.cents + b.cents }, Money) end
Money.__tostring = function(m) return string.format("$%.2f", m.cents / 100) end

local a = setmetatable({ cents = 150 }, Money)
local b = setmetatable({ cents = 275 }, Money)
print(tostring(a + b))   -- $4.25

setmetatable(t, mt) attaches mt to t and returns t. Common metamethods: __add, __sub, __mul, __eq, __lt, __tostring, __len, __index.

__index: methods and classes

When you read a key a table does not have, Lua looks in the metatable's __index. Pointing __index at a table of functions gives every object the same methods. That is how Lua does classes:

local Dog = {}
Dog.__index = Dog

function Dog.new(name)
  return setmetatable({ name = name }, Dog)
end

function Dog:speak()          -- the colon adds a hidden first parameter: self
  return self.name .. " says woof"
end

local rex = Dog.new("Rex")
print(rex:speak())            -- Rex says woof

rex:speak() is short for rex.speak(rex). The table rex has no speak, so Lua finds it through __index in Dog.

Your task

Build a Vector "class":

  1. Vector.new(x, y) creates a vector.
  2. + adds two vectors (__add).
  3. tostring(v) gives "(3, 4)" (__tostring).
  4. v:length() returns the length, sqrt(x² + y²), as a shared method (__index).
main.lua
Vector = {}

-- your code here

local v = Vector.new(3, 4)
print(tostring(v + Vector.new(1, 1)))
print(v:length())

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…