typestar

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

  1. Vec.__add runs when + meets two vectors.
  2. __tostring feeds print and tostring.
  3. The constructor stamps each table with setmetatable.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Metatables, step 18 of 27 in Language basics.

← Previous Next →