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

_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.
class (base, c_arg, c) create a new class, derived from a given base class.


Functions

_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
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
generated by LDoc 1.4.6 Last updated 2022-04-25 14:03:04