Advertisement
Guest User

Untitled

a guest
Dec 7th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. @-- Class.lua
  2. -- Compatible with Lua 5.1 (not 5.0).
  3.  
  4. function class(base)
  5. local c = {} -- a new class instance
  6. if type(base) == 'table' then
  7. -- our new class is a shallow copy of the base class!
  8. for i,v in pairs(base) do
  9. c[i] = v
  10. end
  11. c._base = base
  12. end
  13.  
  14. -- the class will be the metatable for all its objects,
  15. -- and they will look up their methods in it.
  16. c.__index = c
  17.  
  18. -- expose a constructor which can be called by <classname>(<args>)
  19. local mt = {}
  20. mt.__call = function(class_tbl, ...)
  21. local obj = {}
  22. setmetatable(obj,c)
  23. if class_tbl.init then
  24. class_tbl.init(obj,...)
  25. else
  26. -- make sure that any stuff from the base class is initialized!
  27. if base and base.init then
  28. base.init(obj, ...)
  29. end
  30. end
  31.  
  32. return obj
  33. end
  34.  
  35. c.is_a = function(self, klass)
  36. local m = getmetatable(self)
  37. while m do
  38. if m == klass then return true end
  39. m = m._base
  40. end
  41. return false
  42. end
  43.  
  44. setmetatable(c, mt)
  45. return c
  46. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement