为什么一个人工作和一个崩溃? [英] Why does one work and one crash?
问题描述
这已经驱使我坚持了一个多星期。以下是游戏中的机器人播放器的两个Lua代码片段 Bitfighter (使用C ++编写,使用LuaWrapper的变体绑定)。
This has been driving me nuts for over a week. Below are two snippets of Lua code from a robot player in the game Bitfighter (written in C++, using a variant of LuaWrapper for binding).
当我第一次启动Lua脚本时,两者的工作方式完全相同。但是经过几分钟的强烈的对象创建和破坏,变体2停止工作,并给我以下错误:
When I first start the Lua script, both work exactly as expected. But after some minutes of intense object creation and destruction, variant 2 stops working, and gives me the following error:
robot.lua:253: attempt to call missing or unknown method 'getEnergy' (a nil value)
这些应该功能相同。谁能解释这些差异?
To my eyes these should function identically. Who can explain the difference?
注意:target是一个表示C ++对象的(重)userdata。 getEnergy和getHealth是正确注册的C ++函数。我可以很容易地再现这种不同的行为。这是Lua 5.1,使用luavec mod。
Notes: target is a (heavy) userdata representing a C++ object. getEnergy and getHealth are properly registered C++ functions. I can reproduce this differing behavior easily. This is Lua 5.1, using the luavec mod.
变体1 - 总是工作
Variant 1 - always works
local mt = getmetatable(target)
local pow = mt.getEnergy(target) + mt.getHealth(target)
变体2 - 在脚本运行任意时间后启动失败
Variant 2 - starts failing after script has been running for an arbitrary amount of time
local pow = target:getEnergy() + target:getHealth()
推荐答案
要跟踪停止工作时会发生什么,您可以在 pcall
中打包调用,并查看目标
value:
To track what happens when it stops working you can wrap the call in pcall
and explore what happened with the 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
这篇关于为什么一个人工作和一个崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!