Skip to content
Enrique García edited this page Mar 25, 2016 · 7 revisions

Metamethods can do funky stuff like allowing additions in our instances.

Let’s make an example with __tostring

Point = class('Point')
function Point:initialize(x,y)
  self.x = x
  self.y = y
end
function Point:__tostring()
  return 'Point: [' .. tostring(self.x) .. ', ' .. tostring(self.y) .. ']'
end

p1 = Point(100, 200)
p2 = Point(35, -10)
print(p1)
print(p2)

Output:
Point: [100, 200]
Point: [35, -10]

Middleclass 4.x supports all the Lua metamethods. There are some restrictions:
  • Overriding the `metatable` metamethod is possible, but likely will give you trouble. Do this only if you know what you are doing.
  • Metamethods not supported by the Lua version being used are not supported. For example, the `len` metamethod does not work in Lua 5.1 or LuaJIT without 5.2 compatibility.
Clone this wiki locally