我使用 LuaBind 在我的 C++ 应用程序中嵌入了 Lua。我需要有在多次运行中持续存在的变量,运行相同文件名的其他对象无法访问这些变量。
例如:假设我有一个名为NPC
的类。 NPC
持有一个字符串,即他们运行的脚本的名称。创建NPC
时,会创建一个名为Health
的变量。当 NPC
被击中时,他们会失去 5 点生命值。脚本在 Lua 中是这样的:
local health = 10
function onHit()
health = health - 5
end
我遇到的问题是每个运行此脚本的 NPC
都没有自己的健康实例。例如,假设我创建了 NPC A
,并从其生命值中减去 5。然后,我创建了 NPC B
。因为它将生命值重置回 10,所以如果我告诉 NPC A
打印生命值,它会返回 10,即使它应该是 5。
如果我要为每个对象设置一个不同的 Lua 实例,那么它会以这种方式工作,但在那种情况下我最终会一次拥有数百个实例,我知道这不是一件好事。
有没有办法让变量在 Lua 中像这样工作?如果没有,是否有一种脚本语言可以像这样高效地工作?
作为引用,这是我正在测试的代码:
路亚:
local health = 10;
function onHit()
health = health - 5
print_out(health)
end
C++:
class NPC
{
public:
NPC(lua_State* inState);
void onHit();
const char* behavior;
lua_State* luaState;
};
NPC::NPC(lua_State* inState)
{
luaState = inState;
behavior = "testBehavior.lua";
luaL_dofile(luaState, behavior);
}
void NPC::onHit()
{
luaL_loadfile(luaState, behavior);
luabind::call_function<int>(luaState, "onHit");
}
void print_out(int number) {
cout << "Health : " << number << endl;
}
int main()
{
lua_State *myLuaState = luaL_newstate();
luabind::open(myLuaState);
luabind::module(myLuaState) [
luabind::def("print_out", print_out)
];
NPC test(myLuaState);
NPC test2(myLuaState);
test.onHit();
test2.onHit();
test.onHit();
lua_close(myLuaState);
}
最佳答案
你可以查看 Lua 的 closures .它看起来像这样:
function healthPoints()
local health = 10
return function()
health = health - 5
return health
end
end
实际情况是每个 NPC 都有自己的功能和自己的计数器。每次它们被击中时,您只需调用 onHit
函数。你会像这样使用它:
npc1.onHit = healthPoints()
npc2.onHit = healthPoints()
npc1.onHit() -- Now at 5, while npc2 is still at 10
您可以像这样添加参数:
function healthPoints(hp)
local health = hp
return function(dmg)
health = health - dmg
return health
end
end
npc1.onHit = healthPoints(100)
npc1.onHit(-12)
我觉得值得一试。
关于python - 嵌入在 C++ 中的 Lua 是否能够拥有持久的局部变量?如果没有,是否有脚本语言可以做到?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087686/