我在创建多个Lua环境时无法在同一个lua_State中运行多个类似的脚本。 程序崩溃并出现以下错误
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
这里是Script.Compile和Script.runFunc方法:
void Script::Compile() {
if (m_filename.IsEmpty()) return;
if (m_filename.Contains("res:")) {
astd::String file = m_filename.Replace("res:", "");
astd::String filecontent = AEIO::OpenTextFromAssetPack(file);
m_lua->RunString(filecontent);
} else {
m_lua->RunScript(m_filename);
}
astd::String id = astd::String("file") + astd::String(UID);
lua_setfield(m_lua->State(), LUA_REGISTRYINDEX, id.CStr());
UID++;
}
void Script::runFunc(astd::String func) {
astd::String id = astd::String("file") + astd::String(UID);
lua_State* state = m_lua->State();
// Weird behaviour during debug.
// The debugger goes back and forth on these 2 lines.
lua_getfield(state, LUA_REGISTRYINDEX, id.CStr());
lua_getfield(state, -1, func.CStr()); // CRASH!
if (lua_isfunction(state, -1)) {
lua_pcall(state, 0, 0, 0);
}
luabind::globals(state)["self"] = m_owner;
}
这是脚本的基本结构:
print("Script Created") --Gets printed before the error occurs.
function onInit()
print("Script Initialized")
end
function onUpdate()
print("Script Update")
end
只有在我拨打runFunc("onInit")
或runFunc("onUpdate")
时才会失败。
提前致谢。