Skip to content
JabDoesThings edited this page Nov 17, 2024 · 2 revisions

Class is a library imported from http://lua-users.org/wiki/SimpleLuaClasses

Using class works as follows:

Definition

--- (Sub-Class call)
---
--- @param base table The super-class to extend.
--- @param init function The constructor function, passing the instance as the first argument.
local class = function(base, init) end

--- (Class call)
---
--- @param init function The constructor function, passing the instance as the first argument.
local class = function(init) end

Methods

--- @param type table The defined class object.
--- 
--- @return boolean True if the class-instance object is of the type.
function class:is_a(type) end

--- @param ins table The class-instance object to initialize.
--- @param args ... Any arguments provided to the constructor.
--- 
--- @return void
function class:init(ins, args) end

Example: Animals

    require 'asledgehammer/util/class';

    local Animal = class(function(ins, name)
        ins.name = name;
    end);

    function Animal:__tostring()
        return self.name .. ': ' .. self:speak();
    end

    local Dog = class(Animal);

    function Dog:speak()
        return 'bark';
    end

    local Cat = class(Animal, function(ins, name, breed)
        Animal.init(ins, name);  -- must init base!
        ins.breed = breed;
    end);

    function Cat:speak()
        return 'meow';
    end

    local Lion = class(Cat);

    function Lion:speak()
        return 'roar';
    end

    local fido = Dog('Fido');
    local felix = Cat('Felix', 'Tabby');
    local leo = Lion('Leo', 'African');
Clone this wiki locally