I have embedded Lua in my C++ application using LuaBind. I need to have variables that persist across multiple runs, that can't be accessed by other objects that run the same file name.
For example: let's say I have a class called NPC
. An NPC
holds a string, that is the name of the script they run. When an NPC
is created, a variable is created called Health
. When an NPC
is hit, they lose 5 health. The scripts would be something like this in Lua:
local health = 10
function onHit()
health = health - 5
end
The issue I have with this is that every NPC
that runs this script, doesn't have their own instance of health. For example, let's say I create NPC A
, and subtract 5 from its health. Then, I create NPC B
. Because it resets health back to 10, if I tell NPC A
to print health, it gives me back 10, even though it should be 5.
If I were to have a different Lua instance for every object, then it would work that way, but I would end up with hundreds of instances at a time in that case, which I understand is not a good thing.
Is there a way to have variables work like this in Lua? If not, is there a scripting language that will work like this in an efficient manner?
For reference, here is the code I am testing:
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);
}