Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function C(v, t) return type(v) == t and v end -- checking shortcut
- local function Class(a, b) -- "a" and "b" is class_name and parent_class in any order (both optional)
- local smt, gmt = setmetatable, getmetatable
- local mt, cl = {}, {}
- mt.__index = C(a, 'table') or C(b, 'table') -- parent class, if exists
- mt.__call = function(self, ...)
- local o = smt({}, cl) -- new obj
- local init = cl.init or cl.new
- if not init then return o end -- without init func - fine too
- return o, init(o, ...) -- return obj and any returns of init func
- end
- cl.__name = C(a, 'string') or C(b, 'string') or 'class:'..tostring(cl):match("0x%x+")
- cl.__index = cl -- looping, but metamethod access
- cl.Super = mt.__index -- access to parent class with obj.Super.foo(obj)
- cl.Type = function(self, obj) return C(obj, 'table') and gmt(obj) == gmt(self) or cl.__name end
- cl.IsObjectOf = function(self, class) return rawequal(class, gmt(self)) end
- return smt(cl, mt)
- end
- if ... then return Class end
- -- testing and examples
- Foo = Class('Yo')
- function Foo:init(x, y) -- same as Foo:new(x, y)
- self.x, self.y = x, y
- return 'qwe', 'rty'
- end
- function Foo:print()
- print(self.x, self.y)
- end
- fo, a, b = Foo(10, 20)
- fo:print() -- 10, 20
- print(a, b) -- qwe rty
- Bar = Class(Foo, 'Yoyoyo') -- table as parent, string as class-name
- function Bar:init(x, y, w, h)
- self.Super.init(self, x, y) -- parent class methods (overrided)
- self.w, self.h = w, h
- end
- function Bar:printf()
- print(self.x, self.y, self.w, self.h)
- end
- bar = Bar(10, 20, 30, 40)
- bar:print() -- 10 20
- bar:printf() -- 10 20 30 40
- debug.debug()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement