Skip to content

Instantly share code, notes, and snippets.

@rtoal
Created March 14, 2015 19:31
Show Gist options
  • Save rtoal/19f5313d4bdee7a48ebc to your computer and use it in GitHub Desktop.
Save rtoal/19f5313d4bdee7a48ebc to your computer and use it in GitHub Desktop.
Example of an interesting class pattern in Lua, with operator overloading
Vector = (function (class, meta, prototype)
class.new = function (i, j)
return setmetatable({i = i, j = j}, meta)
end
prototype.magnitude = function (self)
return math.sqrt(self.i * self.i + self.j * self.j)
end
meta.__index = prototype
meta.__add = function (self, v)
return class.new(self.i + v.i, self.j + v.j)
end
meta.__mul = function (self, v)
return self.i * v.i + self.j * v.j
end
meta.__tostring = function (self)
return string.format('<%g,%g>', self.i, self.j)
end
return class
end)({}, {}, {})
u = Vector.new(3, 4)
v = Vector.new(-5, 10)
print(u.i) -- <3,4>
print(u.j) -- <-5,10>
print(u:magnitude()) -- 5.0
print(u + v) -- <-2,14>
print(u * v) -- 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment