【问题标题】:How to set global C++ pointer for lua_State如何为 lua_State 设置全局 C++ 指针
【发布时间】: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;

标签: c++ lua


【解决方案1】:

将指针作为轻量级用户数据推送到同一模块中可能是最简单的。这样,您可以轻松地从每个 Lua 函数中访问资源,只需将其作为参数传递即可。

您还可以使用一个上值,它在 C 闭包中隐式可用,而无需将其作为参数传递。我已经在别处回答过这个问题:https://stackoverflow.com/a/51337524

#include <lua.hpp>

struct Context {
    int i;
};

int fn_one(lua_State *L)  {
    luaL_checkany(L, 1);
    Context *context = static_cast<Context *>(lua_touserdata(L, 1));
    lua_pushinteger(L, context->i);
    return 1;
}

extern "C" int luaopen_example (lua_State *L) {
    Context *context = new Context{42};
    lua_newtable(L);
    lua_pushcfunction(L, fn_one);
    lua_setfield(L, -2, "one");
    lua_pushlightuserdata(L, context);
    lua_setfield(L, -2, "ctx");
    return 1;
}
local ex = require("example")
print(ex.ctx)
print(ex.one(ex.ctx))
$ g++ -Wall -Wextra -Wpedantic -I /usr/include/lua5.3/ -shared -fPIC -o example.so example.cpp
$ lua5.3 test.lua
userdata: 0x55a81d6af920
42

Live example on Wandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 2011-03-08
    • 2020-08-04
    • 2011-06-29
    相关资源
    最近更新 更多