Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

what, specifically, does class() do?

in Questions Posts: 1,089

i'm wanting to do some tricky stuff with classes and metatables. it would be very helpful if @Simeon or someone could post the exact code for class() in whatever language it exists. thanks!

Comments

  • SimeonSimeon Admin Mod
    Posts: 5,693

    Here is the code

    -- Class.lua
    
    function class(base)
        local c = {}    -- a new class instance
        if type(base) == 'table' then
            -- our new class is a shallow copy of the base class!
            for i,v in pairs(base) do
                c[i] = v
            end
            c._base = base
        end
    
        -- the class will be the metatable for all its objects,
        -- and they will look up their methods in it.
        c.__index = c
    
        -- expose a constructor which can be called by <classname>(<args>)
        local mt = {}
        mt.__call = function(class_tbl, ...)
            local obj = {}
            setmetatable(obj,c)
            if class_tbl.init then
                class_tbl.init(obj,...)
            else 
                -- make sure that any stuff from the base class is initialized!
                if base and base.init then
                    base.init(obj, ...)
                end
            end
    
            return obj
        end
    
        c.is_a = function(self, klass)
            local m = getmetatable(self)
            while m do 
                if m == klass then return true end
                m = m._base
            end
            return false
        end
    
        setmetatable(c, mt)
        return c
    end
    
  • Posts: 1,089

    thanks!

Sign In or Register to comment.