revolucas

(Lua) Simple Class

Feb 4th, 2017
296
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.55 KB | None | 0 0
  1. --[[
  2. author: Alundaio (aka Revolucas)
  3. A function that creates a new class-like table suitable for combining table properties.
  4. It is very simple, only 20 lines and it is very aesthetically pleasing to define new 'classes'
  5. ex 1. Class "new_class"
  6. ex 2. Class "new_class" (inherit)
  7. ex 3. Class "new_class" (inherit1,inherit2,...)
  8.  
  9. The only requirement is that you need to give _G a metatable where 'this' returns the table
  10. being indexed, which in my opinion is useful on it's own as it will return the current table
  11. environment.
  12.  
  13. example usage:
  14.  
  15. Class "human"
  16. function human:__init(name)
  17.     self.name = name
  18. end
  19. function human:printf()
  20.     print(self.name)
  21. end
  22.  
  23. Class "girl" (human)
  24. function girl:__init(name)
  25.     self.inherited[1].__init(self,name)
  26. end
  27.  
  28. Class "boy" (human)
  29. Class "transgender" (boy,girl)
  30.  
  31. local instance = transgender("bob")
  32. instance:printf() -- prints 'bob'
  33. --]]
  34.  
  35. -- Set _G metatable where 'this' returns self of __index.
  36. setmetatable(_G, {__index=function(t,k)
  37.     if (k == "this") then
  38.         return t
  39.     end
  40.     return rawget(_G,k)
  41. end
  42. })
  43.  
  44. function Class(name)
  45.     this[name] = setmetatable({},{
  46.         __index = getmetatable(_G).__index,
  47.         __call = function(t,...)
  48.             local o = setmetatable({},{__index=t})
  49.             o:__init(...)
  50.             return o
  51.         end
  52.     })
  53.     return function(...)
  54.         local p = {...}
  55.         this[name].inherited = p
  56.         getmetatable(this[name]).__index=function(t,k)
  57.             for i,v in ipairs(p) do
  58.                 local ret = rawget(v,k)
  59.                 if (ret ~= nil) then
  60.                     return ret
  61.                 end
  62.             end
  63.             return getmetatable(_G).__index(_G,k)
  64.         end
  65.     end
  66. end
Advertisement
Add Comment
Please, Sign In to add comment