Skip to content

Instantly share code, notes, and snippets.

@ochaton
Created May 20, 2018 09:35
Show Gist options
  • Save ochaton/1eacfbb444e4445fe7f0333896a0a857 to your computer and use it in GitHub Desktop.
Save ochaton/1eacfbb444e4445fe7f0333896a0a857 to your computer and use it in GitHub Desktop.
metaclass
local Fabric = {}
Fabric.__metatable = {}
setmetatable(Fabric, Fabric.__metatable)
local Class = {}
Class.__metatable = {}
setmetatable(Class, Class.__metatable)
function Class.__metatable:__call(classname)
local mt = {
__name = classname,
__index = Class,
__call = Class.instance_object,
}
return setmetatable({
implements = {},
expects = {},
abstract = true,
__metatable = mt,
}, mt)
end
function Class:instance_object(...)
local mt = self.__metatable
self.__metatable = nil
setmetatable(self, {
__index = self.parent
})
local args = {}
if select("#", ...) == 1 and type(...) == "table" then
args = ...
end
local object = setmetatable(args, {
__index = self,
__name = mt.__name,
})
if type(self.constructor) == 'function' then
object = object:constructor(...) or object
end
return object
end
function Class:inherits(...)
local numargs = select("#", ...)
if numargs ~= 1 then
error("Expected exactly 1 class to inherit", 2)
end
local parent = ...
parent = Fabric[parent]
if not parent then
error(string.format("Parent class '%s' not found", ...), 2)
end
self.parent = parent
return self
end
function Fabric.__metatable:__call(name)
if Fabric[name] then
error(string.format("Class %s is already exists", name), 2)
end
local class = Class(name)
Fabric[name] = class
Fabric[class] = class
return class
end
return Fabric
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment