Metamethods in Lua
__add and __tostring teach operators new types.
-- Metamethods teach operators new types: __add, __tostring.
local Vec = {}
Vec.__index = Vec
function Vec.new(x, y)
return setmetatable({ x = x, y = y }, Vec)
end
Vec.__add = function(a, b)
return Vec.new(a.x + b.x, a.y + b.y)
end
Vec.__tostring = function(v)
return "(" .. v.x .. ", " .. v.y .. ")"
end
local step = Vec.new(1, 0) + Vec.new(0, 2)
print("Player moves " .. tostring(step))
print(tostring(step + Vec.new(3, 3)))
How it works
Vec.__addruns when + meets two vectors.__tostringfeeds print and tostring.- The constructor stamps each table with
setmetatable.
Keywords and builtins used here
Vecendfunctionlocalnewprintreturnsetmetatabletostring
The run, in numbers
- Lines
- 19
- Characters to type
- 430
- Tokens
- 138
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 127 seconds.
Step 2 of 3 in Metatables, step 18 of 27 in Language basics.