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":
Vector.new(x, y)creates a vector.+adds two vectors (__add).tostring(v)gives"(3, 4)"(__tostring).v:length()returns the length,sqrt(x² + y²), as a shared method (__index).