Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local tinsert = table.insert
- local tremove = table.remove
- local tostring = tostring
- local setmetatable = setmetatable
- local getmetatable = getmetatable
- local next = next
- local _G = _G
- function super(obj)
- local new = {}
- for k, v in next, obj do
- new[k] = v
- end
- return setmetatable(new, getmetatable(obj).super)
- end
- function class(name, statics, methodes, parentClass, metaBase)
- local classTbl = {__parentClass = parentClass}--The actual class table
- if(parentClass) then--we require a reference to the parent class
- classTbl.super = parentClass.__methodes
- end
- if(not methodes.__tostring) then--implementing tostring if not existant
- methodes.__tostring = function(self)
- return name
- end
- end
- if(methodes[name]) then
- methodes.__construct = methodes[name]
- end
- assert(methodes.__construct, "No constructor defined for :"..name)
- if(parentClass) then
- for k, v in next, parentClass.__methodes do--copying methodes from superclass
- if(not methodes[k]) then
- methodes[k] = v
- end
- end
- end
- if(methodes.__call) then
- methodes.__call = nil
- end
- classTbl.__methodes = methodes--needed for later access
- methodes.__classTbl = classTbl
- classTbl.__methodes.__index = methodes--Required
- local ClassMeta = {--Class metatable needed to "call" the class itself
- __call = function(self, ...)--constructor
- local instance = setmetatable({}, methodes)--required
- if(self ~= classTbl) then
- instance = self--allow call override
- else
- instance = {}
- end
- if(parentClass and self == classTbl) then
- local currParent = parentClass
- local constructorStack = {instance.__construct}--the constructors need to be called in the opposite inheritance order
- while currParent do
- if(not currParent.__methodes.__construct) then--If we have a superclass
- break
- end
- tinsert(constructorStack, currParent.__methodes.__construct)--pushing the function onto the stack
- currParent = currParent.__parentClass
- end
- while(constructorStack[1]) do--calling all constructors
- tremove(constructorStack)(instance, ...)--hacky :3
- end
- elseif(self == classTbl) then
- instance:__construct(...)
- end
- return instance
- end
- }
- for k, v in next, statics do--copy statics into our table
- ClassMeta[k] = v
- end
- _G["Is"..name] = function(obj)
- local meta = getmetatable(obj).__classTbl
- while(meta.__classTbl.__parentClass) do
- if(meta.__classTbl.__parentClass == classTbl) then
- return true
- end
- meta = meta.__parentClass
- end
- return false
- end
- if(parentClass) then--copying statics
- for k, v in next, getmetatable(parentClass) do
- if(not ClassMeta[k]) then
- ClassMeta[k] = v
- end
- end
- end
- ClassMeta.__index = ClassMeta--required
- setmetatable(classTbl, ClassMeta)--required
- return classTbl
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement