Skip to content

Instantly share code, notes, and snippets.

@variousauthors
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save variousauthors/11280004 to your computer and use it in GitHub Desktop.
Save variousauthors/11280004 to your computer and use it in GitHub Desktop.
I wanted to be able to copy my instances!
-- @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