将纯lua对象传递给C函数并获取值

在 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)
{
   void* obj = lua_topointer(l, 1);            //I hope get lua's a variable
   lua_pushlightuserdata(l, obj);
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, 1);        //I hoe get the value "abc123"
   ...
   return 0;
}

但是我的 C 结果是

id = null

为什么?如何修改代码使其正常工作?

PS:我不希望创建映射到 Lua 的 C Test 类

点赞
用户416047
用户416047

也许这样 - 抱歉未测试 - 没有方便的编译器。

输入是堆栈顶部的 Lua 表,所以 getfield(l,1,"ID") 应该从堆栈顶部的表中获取 ID 字段 - 在本例中是您的输入表。它然后将结果推送到堆栈顶部。

int callCfunc(lua_State * l)
{
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, 1);        //我希望获得值"abc123"
   ...
   return 0;
}
2013-01-08 07:07:24
用户364126
用户364126

我找到了原因

正确的 C 代码应该是 ...

C 代码

int callCfunc(lua_State * l)
{
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, -1);        //-1
   ...
   return 0;
}
2013-01-08 08:21:45