这已经让我抓狂了一个多星期了。下面是游戏中机器人玩家的两段 Lua 代码片段比特战士 http://bitfighter.org(用 C++ 编写,使用 LuaWrapper 的变体进行绑定)。
当我第一次启动 Lua 脚本时,两者都完全按预期工作。但经过几分钟的密集对象创建和销毁后,变体 2 停止工作,并给出以下错误:
robot.lua:253: attempt to call missing or unknown method 'getEnergy' (a nil value)
在我看来,它们的功能应该是相同的。谁能解释一下其中的区别?
注意:target 是代表 C++ 对象的(重)用户数据。 getEnergy 和 getHealth 是正确注册的 C++ 函数。我可以轻松地重现这种不同的行为。这是 Lua 5.1,使用 luavec mod。
变体 1 - 始终有效
local mt = getmetatable(target)
local pow = mt.getEnergy(target) + mt.getHealth(target)
变体 2 - 脚本运行任意时间后开始失败
local pow = target:getEnergy() + target:getHealth()
要跟踪它停止工作时发生的情况,您可以将调用包装起来pcall
并探索发生了什么target
value:
local ok, res = pcall(function() return target:getEnergy() + target:getHealth() end)
if not ok then
local s = "Invalid target value: "..tostring(target).." "..type(target).."\n"
for k, v in pairs(target) do s = s.."target "..tostring(k).." "..tostring(v).."\n" end
for k, v in pairs(getmetatable(target)) do s = s.."meta "..tostring(k).." "..tostring(v).."\n" end
-- add anything else that helps you figure out what happened to target
error(res..s)
end
local pow = res
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)