Lua继承

我在 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())

我想让 test2test 继承,但保留指定的 test2 方法 bye。除 bye:method 外,一切正常。

我该如何解决这个问题?

原文链接 https://stackoverflow.com/questions/6917516

点赞
stackoverflow用户151501
stackoverflow用户151501

你在test2:create_inst()中返回了一个空表,任何时候都没有引用test2,因此test2:bye()函数不在由test2:create_inst()返回的表中。

2011-08-02 20:04:12
stackoverflow用户88888888
stackoverflow用户88888888

在你的代码中,test2 实际上与你正在实例化的表没有任何关系,从 test2:create_inst 返回的 new_class 表是新实例。因此,它自然没有名为 bye 的字段。简单修改:

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
2015-05-08 21:56:05
stackoverflow用户7107815
stackoverflow用户7107815

我认为答案想要实现多继承,即 “new_class” 继承 “test2” 和 “baseClass”。

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

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

c = class(test2, baseClass):new{}
print(c.test1Data, c.passData, c:hello(), c:bye())
2017-04-14 02:42:13