开发者

Lua inheritance

I have two classes in Lua.

test1 = {test1Data = 123, id= {0,3}}
function test1:hello()
    print 'HELLO!'
end
function test1:new (inp)
    inp = inp or {}
    setmetatable(inp, self)
    self.__index = self
    return inp
end

test2 = {}
function test2:bye ()
    print 'BYE!'
end
function test2:create_inst( baseClass )
    local new_class = {}
    local class_mt = { __index = new_class }
    function new_class:create()
        local newinst = {}
        setmetatable( newinst, class_mt )
        return newinst
    end
    if baseClass then
        setmetatable( new_class, { __index = baseClass } )
    end

    return new_class
end

a =开发者_运维技巧 test1:new({passData='abc'})
print (a.test1Data, a.passData, a:hello())
c = test2:create_inst(a)
print (c.test1Data, c.passData,c:hello(), c:bye())

I want to inherit test2 from test but leave in the specified test2 methods bye. Everything works except for bye:method. How can I solve this problem?


You return an empty table in test2:create_inst(), at no point does anything reference test2, so the function test2:bye() is not in the table returned by test2:create_inst()


In your code, test2 actually has nothing to do with the table you are instancing, this new_class table you return from test2:create_inst is the new instance. So naturally it has no field named bye. Simple modification:

function test2:create_inst( baseClass )
    ...
    if baseClass then
        setmetatable( new_class, { __index = baseClass } )
    end
    ...

    function new_class:bye()
        print("bye!")
    end
    return new_class
end


I think the answer want to implement Multi-Inheritance that new_class inherit "test2" and "baseClass".

local function search(k, objlist)
    local i = 0
    local v
    while objlist[i] then
        v = objlist[i][k] 
        if v then return v end
    end
end

function class(...)
    local parents = (...)
    local object = {}
    function object:new(o)
        o = o or {}
        setmetatable(o, object)
        return o
    end
    object.__index = object
    setmetatable(object, 
        {__index=function(t, k)
        search(k, parents)    
    end})
    return object
end

c = class(a, test2)
print(c.test1Data, c.passData,c:hello(), c:bye())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜