dcubix
dcubix

Reputation: 187

Multiple Lua environments issue

I'm having trouble on creating multiple Lua environments to run multiple similar scripts in the same lua_State. The program crashes with the following error

PANIC: unprotected error in call to Lua API (attempt to index a nil value)

Here's the Script.Compile and Script.runFunc methods:

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;
}

And this is the basic structure of the scripts:

print("Script Created") --Gets printed before the error occurs.

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

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

And it only fails when I call runFunc("onInit") or runFunc("onUpdate").

Thanks in advance.

Upvotes: 0

Views: 274

Answers (0)

Related Questions