Last active
August 29, 2015 14:00
-
-
Save variousauthors/11280004 to your computer and use it in GitHub Desktop.
I wanted to be able to copy my instances!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- @param _construct: map args --> object | |
-- @param tcurtsnoc_: map object --> args | |
Klass = function (_construct, tcurtsnoc_) | |
local constructor | |
local function copy(o) | |
return constructor(tcurtsnoc_(o)) | |
end | |
constructor = function (...) | |
local instance = _construct(unpack({...})) | |
instance.copy = function () | |
return copy(instance) | |
end | |
return instance | |
end | |
return constructor | |
end | |
Point = Klass((function () | |
local constructor = function (x, y) | |
local x, y = x, y | |
local instance = { | |
getX = function () | |
return x | |
end, | |
getY = function () | |
return y | |
end, | |
setX = function (n) | |
x = n | |
end, | |
setY = function (n) | |
y = n | |
end, | |
} | |
return instance | |
end | |
local copy = function (o) | |
return o.getX(), o.getY() | |
end | |
return constructor, copy | |
end)()) | |
Vector = Klass((function () | |
local constructor = function (x, y) | |
local p = Point(x, y) | |
p.length = function () | |
return math.sqrt(p.getX() ^ 2 + p.getY() ^ 2) | |
end | |
-- returns a new vector with a length of 1 | |
p.to_unit = function () | |
local mag = p.length() | |
return Vector(p.getX() / mag, p.getY() / mag) | |
end | |
return p | |
end | |
local copy = function (o) | |
return o.getX(), o.getY() | |
end | |
return constructor, copy | |
end)()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment