Lua继承 [英] Lua inheritance

查看:119
本文介绍了Lua继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Lua中有两个类。

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

我想继承 test2 code>测试,但保留指定的 test2 方法 bye
除了 bye:method ,一切正常。
我如何解决这个问题?

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?

推荐答案

test2中返回一个空表: create_inst(),没有任何引用 test2 ,所以函数 test2:bye()不在 test2:create_inst()

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

这篇关于Lua继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆