Appkit: /class.lua — code sample - Stingray Lua API Reference

Appkit: /class.lua — code sample

Code

--[[

Helper function to implement object oriented class objects. Returns a lua object
that has its __call metatable function set so that it can be used as a function to
create new "instances" of the class type.

Usage:

    SomeClass = Appkit.class(SomeClass)

    -- An instance is created like so
    local instance = SomeClass(world)

    -- Class types receive an init function call
    function SomeClass.init(world)
        -- Perform initialization
        self.world = world
        -- etc
    end

]]--
Appkit = Appkit or {}
-- Returns a class object that can be used to instantiate class objects. If
-- super is provided, then the class will copy all pairs (variables and
-- functions) from super.
function Appkit.class(class, super)
    -- For hot swapping if no class exists, one will be created
    -- otherwise the existing class will be updated.
    if not class then
        class = {}

        -- Object constructor
        local meta = {}
        meta.__call = function(self, ...)
            local object = {}
            setmetatable(object, class)
            if object.init then object:init(...) end
            return object
        end
        setmetatable(class, meta)
    end

    -- Deep copy the super class functions onto the new class
    -- so that they can be overriden later.
    if super then
        for k,v in pairs(super) do
            class[k] = v
        end
    end

    -- Keep a copy of the base class to simplify
    -- calling the parent functionality when overriding functions.
    class.Super = super

    -- Setup prototype behavior so that class functions are called if instance
    -- does not define/override them.
    class.__index = class

    return class
end