Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Oop Lua遗传_Oop_Class_Inheritance_Lua_Multiple Inheritance - Fatal编程技术网

Oop Lua遗传

Oop Lua遗传,oop,class,inheritance,lua,multiple-inheritance,Oop,Class,Inheritance,Lua,Multiple Inheritance,我在卢阿有两个班 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 () prin

我在卢阿有两个班

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())
我想从
test
继承
test2
,但保留指定的
test2
方法
bye
。 除了
bye:method
之外,一切都正常。
如何解决此问题?

如果在
test2:create_inst()
中返回一个空表,则在任何时候都不会引用
test2
,因此函数
test2:bye()
不在代码中的
test2:create_inst()
返回的表中,
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

我认为答案是要实现新的_类继承“test2”和“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())