Module pl.class
Provides a reuseable and convenient framework for creating classes in Lua.
Two possible notations:
B = class(A) class.B(A)
The latter form creates a named class within the current environment. Note that this implicitly brings in `pl.utils` as a dependency.
See the Guide for further discussion
Functions
class:_init (...) | initializes an __instance__ upon creation. |
instance:is_a (some_class) | checks whether an __instance__ is derived from some class. |
some_class:class_of (some_instance) | checks whether an __instance__ is derived from some class. |
some_class:cast (some_instance) | cast an object to another class. |
instance:base (method_name, ...) | Access to base class methods. |
class (base, c_arg, c) | create a new class, derived from a given base class. |
Functions
- class:_init (...)
-
initializes an __instance__ upon creation.
Parameters:
- ... parameters passed to the constructor
Usage:
local Cat = class() function Cat:_init(name) --self:super(name) -- call the ancestor initializer if needed self.name = name end local pussycat = Cat("pussycat") print(pussycat.name) --> pussycat
- instance:is_a (some_class)
-
checks whether an __instance__ is derived from some class.
Works the other way around as `class_of`.
Parameters:
- some_class class to check against
Returns:
-
`true` if `instance` is derived from `some_class`
Usage:
local pussycat = Lion() -- assuming Lion derives from Cat if pussycat:is_a(Cat) then -- it's true end
- some_class:class_of (some_instance)
-
checks whether an __instance__ is derived from some class.
Works the other way around as `is_a`.
Parameters:
- some_instance instance to check against
Returns:
-
`true` if `some_instance` is derived from `some_class`
Usage:
local pussycat = Lion() -- assuming Lion derives from Cat if Cat:class_of(pussycat) then -- it's true end
- some_class:cast (some_instance)
-
cast an object to another class.
It is not clever (or safe!) so use carefully.
Parameters:
- some_instance the object to be changed
- instance:base (method_name, ...)
-
Access to base class methods.
NOTE: the initializer `_init` has a different way to call its ancestor
Parameters:
- method_name Name of the method to call on the base class
- ... parameters passed to the base class method
Usage:
local Cat = class() function Cat:say(text) print(text) end local Lion = class(Cat) function Lion:say(text) self:base("say", "roar... "..text) end local pussycat = Lion() pussycat:say("hello world") --> 'roar... hello world'
- class (base, c_arg, c)
-
create a new class, derived from a given base class.
Supporting two class creation syntaxes:
either `Name = class(base)` or `class.Name(base)`.
The first form returns the class directly and does not set its `_name`.
The second form creates a variable `Name` in the current environment set
to the class, and also sets `_name`.
Parameters:
- base optional base class
- c_arg optional parameter to class constructor
- c optional table to be used as class