Search code examples
c++multithreadingluaglobal-variables

Using a global lua_State* variable


I want to use a global lua_State* variable in my program, initializing it through a initLua() function and use it to run some Lua functions from main(). When I try it, the Lua code simply won't run. In the future, I want to use an array of Lua states to implement multithreading, where each thread has it's own Lua state.

When I initialize the Lua state inside main(), everything works fine. I'm running W10.

inside cfg.lua:

function teste()
    return 10;
end

in C++, used to set the global state variable *L:

void initLua(lua_State *L) {    
    L = luaL_newstate();
    luaL_openlibs(L);
    luaL_dofile(L, "./cfg.lua");    
}

In main(), int foo(L) calls the teste() function from Lua, and the result is printed.

10 should be printed, but nothing happens when the state variable is being initialized outside main().


Solution

  • First of all, I strongly recommend keeping your Lua state local. It's a lot easier to read code if you can see from the arguments that a function uses the Lua state.

    If you really need to make the Lua state global, then initLua should not have any parameters. Your problem is caused by the fact that you assign to the parameter L and not a global variable.

    Even if your Lua state was local, initLua still should not take a parameter. It could just make a local lua_State * variable and return that.