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())
我想从 test
继承 test2
但保留指定的 test2
方法bye
。 除了 bye:method
之外,一切正常。 我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您在
test2:create_inst()
中返回一个空表,在任何时候都不会引用test2
,因此函数test2:bye()
是不在test2:create_inst()
返回的表中You return an empty table in
test2:create_inst()
, at no point does anything referencetest2
, so the functiontest2:bye()
is not in the table returned bytest2:create_inst()
在您的代码中,
test2
实际上与您正在实例化的表无关,您从test2:create_inst
返回的这个new_class
表是新表实例。所以自然地它没有名为bye
的字段。简单修改:In your code,
test2
actually has nothing to do with the table you are instancing, thisnew_class
table you return fromtest2:create_inst
is the new instance. So naturally it has no field namedbye
. Simple modification:我认为答案是要实现多重继承,即new_class继承“test2”和“baseClass”。
I think the answer want to implement Multi-Inheritance that new_class inherit "test2" and "baseClass".