Search code examples
c++lua

Share data(variables) between lua callback functions in C++


how I can share/access some data inside several lua callback functions in C++? I know that I can use global c++ variables or some singleton but I don't want to use that.

Hypotetic sample:

static int SetParam(lua_State *state) {
  // be able to access nTotalSetParamCalls to do this:
  ++nTotalSetParamCalls;
}

long nTotalSetParamCalls = 0L; // don't want to be it global, I would like to set it to m_luaState and then access it inside callback function
lua_register(m_luaState, "SetParam", SetParam);
luaL_dostring(m_luaState, script);

std::cout << "SetParam was called: " << nTotalSetParamCalls << " times";

Thanx in advance


Solution

  • You can use the following code to save your pointer in the lua state:

    lua_pushlightuserdata(L, new BigObject{});
    lua_setfield(L, LUA_REGISTRYINDEX, "unique-name");
    

    You need to choose this unique-name yourself, see the manual for detail.

    Use the corresponding method to obtain this pointer:

    lua_getfield(L, LUA_REGISTRYINDEX, "unique-name");
    auto bigObject = (BigObject*)lua_touserdata(L, -1);
    lua_pop(L, 1);