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

标签 c++ c lua

在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:我不希望创建 C 测试类映射到 lua

====更新1 ====
另外,我还添加了测试代码来确认传入参数是否正确。

int callCfunc(lua_State * l)
{
   std::string typeName = lua_typename(l, lua_type(l, 1));    // the typeName=="table"
   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;
}

结果

typeName == "table" 

所以传入的参数类型是正确的

最佳答案

我找到原因了
正确的c代码应该是...
在 C 代码中

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

关于c++ - 将纯lua对象传递给C函数并获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208951/

相关文章:

c - 使用 execl 从文件夹中调用文件

从文件未定义行为打印的 C 行

ios - Swift:像 Lua 一样快速从数组中删除元素

c - Lua c lib Windows : The specified procedure could not be found

c++ - 杀死等待条件变量的 pthread

c++ - clang 编译的程序在 std::any_cast 期间抛出 std::bad_any_cast

c++ - 在 C/C++ 中访问 c​​onst 变量的速度

lua - 我应该使用ipairs还是for循环

c++ - 遍历成对的 vector 并访问第一个和第二个元素

c++ - JSONCPP 没有正确读取文件