Advertisement
Snusmumriken

Lua shortest OOP

Apr 21st, 2017 (edited)
348
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.75 KB | None | 0 0
  1. local function C(v, t) return type(v) == t and v end -- checking shortcut
  2.  
  3. local function Class(a, b) -- "a" and "b" is class_name and parent_class in any order (both optional)
  4.   local smt, gmt = setmetatable, getmetatable
  5.   local mt, cl = {}, {}
  6.   mt.__index = C(a, 'table') or C(b, 'table')  -- parent class, if exists
  7.   mt.__call = function(self, ...)
  8.         local o = smt({}, cl)           -- new obj
  9.         local init = cl.init or cl.new
  10.         if not init then return o end   -- without init func - fine too
  11.         return o, init(o, ...)          -- return obj and any returns of init func
  12.     end
  13.   cl.__name = C(a, 'string') or C(b, 'string') or 'class:'..tostring(cl):match("0x%x+")
  14.   cl.__index = cl                              -- looping, but metamethod access
  15.   cl.Super = mt.__index                        -- access to parent class with obj.Super.foo(obj)
  16.   cl.Type = function(self, obj) return C(obj, 'table') and gmt(obj) == gmt(self) or cl.__name end
  17.   cl.IsObjectOf = function(self, class) return rawequal(class, gmt(self)) end
  18.   return smt(cl, mt)
  19. end
  20.  
  21. if ... then return Class end
  22.  
  23. -- testing and examples
  24.  
  25. Foo = Class('Yo')
  26. function Foo:init(x, y) -- same as Foo:new(x, y)
  27.     self.x, self.y = x, y
  28.     return 'qwe', 'rty'
  29. end
  30.  
  31. function Foo:print()
  32.     print(self.x, self.y)
  33. end
  34.  
  35.  
  36. fo, a, b = Foo(10, 20)
  37.  
  38. fo:print()     -- 10, 20
  39. print(a, b)    -- qwe rty
  40.  
  41. Bar = Class(Foo, 'Yoyoyo')     -- table as parent, string as class-name
  42. function Bar:init(x, y, w, h)
  43.     self.Super.init(self, x, y)  -- parent class methods (overrided)
  44.     self.w, self.h = w, h
  45. end
  46.  
  47. function Bar:printf()
  48.     print(self.x, self.y, self.w, self.h)
  49. end
  50.  
  51. bar = Bar(10, 20, 30, 40)
  52.  
  53. bar:print()     -- 10 20
  54. bar:printf()    -- 10 20 30 40
  55. debug.debug()
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement