【问题标题】:How to access lua's object from lua_topointer?如何从 lua_topointer 访问 lua 的对象?
【发布时间】:2013-01-09 18:56:55
【问题描述】:

在 Lua 代码中

Test = {}
function Test:new()
  local obj = {}
  setmetatable(obj, self)
  self.__index = self
  return obj
end
local a = Test:new()
a.ID = "abc123"
callCfunc(a)

在 C 代码中

int callCfunc(lua_State* l)
{
  SetLuaState(l);
  void* lua_obj = lua_topointer(l, 1);            //I hope get lua's a variable
  processObj(lua_obj);
  ...
  return 0;
}

int processObj(void *lua_obj)
{
  lua_State* l = GetLuaState();
  lua_pushlightuserdata(l, lua_obj);              //access lua table obj
  int top = lua_gettop(l);
  lua_getfield(l, top, "ID");                     //ERROR: attempt to index a userdata value
  std::string id = lua_tostring(l, -1);           //I hoe get the value "abc123"
  ...
  return 0;
}

我收到错误:尝试索引用户数据值
如何从 lua_topointer() 访问 lua 的对象?
在 C 中存储一个 lua 对象,然后从 C 中调用它。

【问题讨论】:

    标签: c++ c lua


    【解决方案1】:

    您不应该使用lua_topointer,因为您无法将其转换回 lua 对象,将您的对象存储在 registry 中并传递它的 registry index

    int callCfunc(lua_State* L)
    {
        lua_pushvalue(L, 1);//push arg #1 onto the stack
        int r = luaL_ref(L, LUA_REGISTRYINDEX);//stores reference to your object(and pops it from the stask)
        processObj(r);
        luaL_unref(L, LUA_REGISTRYINDEX, r); // removes object reference from the registry
        ...
    
    
    int processObj(int lua_obj_ref)
    {
        lua_State* L = GetLuaState();
        lua_rawgeti(L, LUA_REGISTRYINDEX, lua_obj_ref);//retrieves your object from registry (to the stack top)
        ...
    

    【讨论】:

      【解决方案2】:

      您不想为该任务使用lua_topointer。事实上,lua_topointer 的唯一合理用途是用于调试目的(如日志记录)。

      由于a 是一个,您需要使用lua_gettable 来访问其中一个字段,或者更简单地使用lua_getfield。当然,您不能将 void* 指针传递给该任务的 processObj,但您可以使用堆栈索引。

      【讨论】:

        猜你喜欢
        • 2021-10-23
        • 2015-11-05
        • 1970-01-01
        • 1970-01-01
        • 2015-06-16
        • 1970-01-01
        • 1970-01-01
        • 2017-12-29
        • 2011-01-15
        相关资源
        最近更新 更多