So I'm working on embedding Lua5.1-2 using LuaJIT in a C++ application and included the ability for lua scripts to "subscribe" to events raised in the C++ code and successfully stored the function reference using luaL_ref and successfully called the function using lua_rawgeti and lua_pcall.
The problem is that after about ~1500 calls to the function the application crashes with no exception thrown. Out of curiosity I decided to monitor the stack before and after calls to the lua function and noticed that lua_gettop starts returning decreasing negative values: ('it' is an iterator to iterate over the current "subscribers", which was only one for testing)
gameClient->appendToLog("Stack size before: " + std::to_string(lua_gettop(L));
lua_rawgeti(L, LUA_REGISTRYINDEX, it->second);
gameClient->appendToLog("Stack size [rawgeti]: " + std::to_string(lua_gettop(L));
int res = lua_pcall(L, 0, 0, 0);
gameClient->appendToLog("Stack size after: " + std::to_string(lua_gettop(L));
The lua function only consists of a logging call for testing:
function update()
log("Lua tick")
end
Here's the output:
Stack size before: 0
Stack size [rawgeti]: 1
Lua tick
Stack size after: 0
Stack size before: 0
Stack size [rawgeti]: 1
Lua tick
Stack size after: 0
... repeats a few hundred times, then ..
Stack size before: 0
Stack size [rawgeti]: 1
Lua tick
Stack size after: -1
Stack size before: -1
Stack size [rawgeti]: 0
Lua tick
Stack size after: -1
... also repeats anywhere from 50-300 times before decreasing yet again
Stack size before: -1
Stack size [rawgeti] 0
Lua tick
Stack size after: -2
Stack size before: -2
Stack size [rawgeti]: -1
Lua tick
Stack size after: -2
This eventually leads to the application crashing. There is no return value or parameters for the lua function so I'm out of ideas.
Note: This happens without the log() call in the lua function, I've already tested this.
Edit: Calling lua_settop(L, 0) after the lua_pcall prevents the crash, but I would still like to know what is causing the problem so that I can fix it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…