Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Class: utilities for setting up inheritace and polymorphism.
- -- Create a class, possibly with a base class.
- -- The metatable and the __index are setup accordingly.
- -- The constructor is accessed by the function call operator.
- -- A default constructor is defined with no parameters,
- -- and it can be overrided by defining an _init method.
- -- Returns the class.
- -- Usage example:
- --
- -- MyClass = Class()
- --
- -- function MyClass:_init(x, y)
- -- if x < 0 then
- -- return nil
- -- end
- --
- -- self.x = x
- -- self.y = y
- -- return self
- -- end
- --
- -- function MyClass:method()
- -- print(self.x, self.y)
- -- end
- --
- --
- -- Derived = Class(MyClass)
- --
- -- function Derived:_init(x)
- -- if not MyClass._init(self, x, x) then
- -- return nil
- -- end
- --
- -- return self
- -- end
- --
- -- function Derived:method()
- -- print(self.x)
- -- end
- --
- --
- -- obj = Derived(5)
- -- obj:method() -- prints "5"
- function Class(base)
- local class = setmetatable(
- {},
- {
- __index = base,
- __call = function (class, ...)
- local self = setmetatable({}, class)
- return type(self._init) == "function" -- check for a user defined constructor.
- and self:_init(...)
- or self
- end
- }
- )
- class.__index = class
- return class
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement