class

From Inspired-Lua Wiki
Revision as of 23:49, 30 May 2011 by Adriweb (talk | contribs) (Created page with "A complete tutorial about classes is written here: http://www.inspired-lua.org/2011/05/5-object-classes/ Here's how the class() function is defined, in the API : <source lang="...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A complete tutorial about classes is written here: http://www.inspired-lua.org/2011/05/5-object-classes/

Here's how the class() function is defined, in the API :

-- Class definition system
class = function(prototype)
    local derived = {}
    local derivedMT = {
        __index = prototype,
        __call  = function(proto, ...)
            local instance = {}
            local instanceMT = {
                __index = derived,
                __call = function()
                    return nil, "attempt to invoke an instance of a class"
                end,
            }
            setmetatable(instance, instanceMT)
            if instance.init then
                instance:init(...)
            end
            return instance
        end,
    }
    setmetatable(derived, derivedMT)
    return derived
end