Skip to content

Instantly share code, notes, and snippets.

@pta2002
Created August 27, 2019 20:48
Show Gist options
  • Save pta2002/4412880cb698f878ce32db91fa368e6e to your computer and use it in GitHub Desktop.
Save pta2002/4412880cb698f878ce32db91fa368e6e to your computer and use it in GitHub Desktop.
-- A stupid way to implement classes.
-- Don't do this.
local classMeta = {}
function classMeta:__call(...)
local obj = setmetatable({}, self)
obj:new(...)
return obj
end
function classMeta:__tostring()
return self.__name
end
function buildClass(body, name)
for k,v in pairs(classMeta) do
body[k] = v
end
body.__name = name
body.__index = body
setmetatable(body, body)
_G[name] = body
end
function class(name)
return function (arg)
if type(arg) == "string" then
return function(body)
for k,v in pairs(_G[arg]) do
if body[k] == nil then
body[k] = v
end
end
buildClass(body, name)
end
elseif type(arg) == "table" then
buildClass(arg, name)
end
end
end
class "Rectangle" {
width = nil,
height = nil,
new = function(self, width, height)
self.width = width
self.height = height
end,
getArea = function(self)
return self.width * self.height
end
}
class "Square" "Rectangle" {
new = function(self, side)
self.width = side
self.height = side
end
}
local rec1 = Rectangle(2, 2)
local rec2 = Rectangle(2, 3)
print(rec1:getArea(), rec2:getArea())
print(Square(3):getArea())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment