Module pl.class

Provides a reusable 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. It has two ways of using; 1) call with a class to check against, 2) call without params.

Parameters:

  • some_class class to check against, or nil to return the class

Returns:

    true if instance is derived from some_class, or if some_class == nil then it returns the class table of the instance

Usage:

    local pussycat = Lion()  -- assuming Lion derives from Cat
    if pussycat:is_a(Cat) then
      -- it's true, it is a Lion, but also a Cat
    end
    
    if pussycat:is_a() == Lion 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.5.0