Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. -- Class: utilities for setting up inheritace and polymorphism.
  2.  
  3.  
  4. -- Create a class, possibly with a base class.
  5. -- The metatable and the __index are setup accordingly.
  6. -- The constructor is accessed by the function call operator.
  7. -- A default constructor is defined with no parameters,
  8. -- and it can be overrided by defining an _init method.
  9. -- Returns the class.
  10. -- Usage example:
  11. --
  12. -- MyClass = Class()
  13. --
  14. -- function MyClass:_init(x, y)
  15. -- if x < 0 then
  16. -- return nil
  17. -- end
  18. --
  19. -- self.x = x
  20. -- self.y = y
  21. -- return self
  22. -- end
  23. --
  24. -- function MyClass:method()
  25. -- print(self.x, self.y)
  26. -- end
  27. --
  28. --
  29. -- Derived = Class(MyClass)
  30. --
  31. -- function Derived:_init(x)
  32. -- if not MyClass._init(self, x, x) then
  33. -- return nil
  34. -- end
  35. --
  36. -- return self
  37. -- end
  38. --
  39. -- function Derived:method()
  40. -- print(self.x)
  41. -- end
  42. --
  43. --
  44. -- obj = Derived(5)
  45. -- obj:method() -- prints "5"
  46. function Class(base)
  47. local class = setmetatable(
  48. {},
  49. {
  50. __index = base,
  51. __call = function (class, ...)
  52. local self = setmetatable({}, class)
  53.  
  54. return type(self._init) == "function" -- check for a user defined constructor.
  55. and self:_init(...)
  56. or self
  57. end
  58. }
  59. )
  60.  
  61. class.__index = class
  62.  
  63. return class
  64. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement