在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/