How would I go about sharing variables in a C++ class with Lua?

人走茶凉 提交于 2019-12-03 16:26:14

One approach is to use

  • a lightuserdata pointing to the C++ variable
  • a C function to access the C++ variable using the lightuserdata
  • keep the lightuserdata as an upvalue of the C function so one function suffices for all variables
  • use the number of arguments to the function to select between getting and setting the variable

For example:

int game_state_var_accessor (lua_State *L)
{
    int *p = lua_topointer(L, lua_upvalueindex(1));
    if (lua_gettop(L) == 0)
    {   // stack empty, so get
        lua_pushinteger(L, *p);
        return 1;
    }
    else
    {   // arg provided, so set
        *p = lua_tointeger(L,1);
        return 0;
    }
}

When you make a new game state you can create accessors for each variable using:

lua_pushlightuserdata(L, (int *)p); // where p points to your variable
lua_pushcclosure(L, game_state_var_accessor, 1);

The accessor is now on the stack and can be bound to a global name, or to the name of a method in a Lua class. If your Lua class table is on the stack at index t this would be:

lua_setfield(L, t, "name_of_accessor");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!