item = {y = 21}
function item:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function item:Run()
print("item running")
end
berry = item:new{x = 52}
function berry:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function berry:Run()
print("berry is running")
self.__index:Run()
end
berry:new{b = 32}:Run()
当它应该打印“berry is running”后跟“item running”时,输出会无限打印“berry is running”。如果我将 self.__index
更改为 self.__index.__index
甚至更改为 self.__index.__index.__index
,输出仍会无限打印“浆果正在运行”。我该如何纠正这个问题?任何帮助将不胜感激
最佳答案
您已经覆盖了berry
中item
的Run
函数,这使得它更难到达。此覆盖会导致无限循环,因为 self.__index
是对 self
的引用,它是一个 berry
。现在 Run
在 berry 中定义 __index
当 berry
被 Run
索引时将不再被调用
所以你的 berry:Run
函数本质上是
function berry:Run()
print("berry is running")
berry:Run()
end
我建议您更改berry:Run
函数,并在其中专门调用item.Run
:
function berry:Run()
print("berry is running")
item.Run(self) -- specifically call item.Run and pass it self.
end
这将为您提供所需的输出:
berry is running
item running
或者,您可以通过在运行前在 berry 中定义它来保留 item:Run
函数:
berry.ParentRun. = berry.Run -- this will cause __index to run and get item:Run
function berry:Run() -- This now defines berry.Run. now __index will no longer run for berry.Run
print("berry is running")
self:ParentRun()
end
奖金说明:
你看到的原因
berry is running
berry is running
item running
评论中的建议是因为运行顺序是
object:Run() -- this calls berry passing the self of object
打印我们的第一个浆果正在运行
现在我们获取那个对象的元表,它是 berry 并调用它运行
berry:Run()
打印我们的第二个浆果正在运行
最后我们得到 berry 的元表,它是 item 并调用它运行
item:Run()
打印项目运行
关于oop - 为什么.__index只返回子类的函数而不返回基类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544441/