多个Lua环境问题

我在创建多个 Lua 环境以在同一 lua_State 中运行多个类似脚本时遇到问题。程序崩溃并显示以下错误:

PANIC: 在调用 Lua API 时出现不受保护的错误(尝试索引为 nil 的值)

这是 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();

    // 在调试期间出现奇怪的行为。
    // 调试器在这两行之间来回跳转。
    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") -- 在出现错误之前会打印。

function onInit()
    print("Script Initialized")
end

function onUpdate()
    print("Script Update")
end

问题仅出现在调用 runFunc("onInit")runFunc("onUpdate") 时。

提前致谢。

点赞