【发布时间】:2019-11-11 12:42:44
【问题描述】:
如何为 lua_State 设置一次全局 c++ 指针。并从 C 函数中获取。
Context *context = new Context();
lua_State *lua = luaL_newstate();
// Store context in lua state
lua_pushcfunction(lua, fn_one);
lua_setglobal(lua, "one");
// Register other global functions
我会从我所有的函数中得到它
int fn_one(lua_State *lua)
{
Context *context = (Context *) lua_touserdata(lua, -1);
// context is null or error get object
return 0;
}
我可以设置一次并使用我所有的全局函数。
这是为了在 Lua 上下文中传递 C++ 指针
【问题讨论】:
-
我将在不同的文件中使用 lua_State。我可以在 lua_State 中存储一些 C++ 指针并从函数中获取它。静态变量不是解决方案。
-
如果您的代码存在于多个源文件中,请考虑使用 extern:
extern lua_State* L = nullptr;