C++ 从C函数中读取嵌套的lua表作为参数对吗?
我将用C语言实现一个函数,它将由Lua脚本调用 这个函数应该接收一个lua表(它甚至包含一个数组)作为参数,所以我应该读取表中的字段。我尝试执行下面的操作,但是我的函数在运行时崩溃了。有人能帮我找到问题吗C++ 从C函数中读取嵌套的lua表作为参数对吗?,c++,c,lua,lua-table,C++,C,Lua,Lua Table,我将用C语言实现一个函数,它将由Lua脚本调用 这个函数应该接收一个lua表(它甚至包含一个数组)作为参数,所以我应该读取表中的字段。我尝试执行下面的操作,但是我的函数在运行时崩溃了。有人能帮我找到问题吗 /* function findImage(options) imagePath = options.imagePath fuzzy = options.fuzzy ignoreColors = options.ignoreColor; ... end
/*
function findImage(options)
imagePath = options.imagePath
fuzzy = options.fuzzy
ignoreColors = options.ignoreColor;
...
end
Call Example:
findImage {
imagePath="/var/image.png",
fuzzy=0.5,
ignoreColors={
0xffffff,
0x0000ff,
0x2b2b2b
}
}
*/
static int findImgProxy(lua_State *L)
{
lua_settop(L, 1);
luaL_checktype(L, 1, LUA_TTABLE);
lua_getfield(L, -1, "imagePath");
lua_getfield(L, -2, "fuzzy");
lua_getfield(L, -3, "ignoreColors");
const char *imagePath = luaL_checkstring(L, -3);
double fuzzy = luaL_optint(L, -2, -1);
int count = lua_len(L, -1); // how to get the member count of ignoreColor array
int colors[count];
for (int i=0; i count; i++) {
lua_rawgeti(L, 4, i);
colors[i] = luaL_checkinteger(L, -1);
lua_pop(L, 1);
}
lua_pop(L, 2);
...
return 1;
}
此代码段看起来不正确(更不用说循环中缺少的比较运算符)。获取表格长度的正确函数是lua\u objlen
。看起来您正试图从“ignoreColor”中获取数字,但尚未首先将它们放在堆栈中。因此,luaL_checkinteger(L,-1-i)代码>最终访问堆栈上的错误索引
您可能需要与此更接近的内容,例如:
int count = lua_objlen(L, -1);
std::vector<int> colors(count);
for (int i = 0; i < count; lua_pop(L, 1))
{
lua_rawgeti(L, 4, ++i);
colors.push_back( luaL_checkinteger(L, -1) );
}
如果要从表中移动大量元素,请确保堆栈上有足够的空间。例如,lua\u checkstack
lua\u len
不返回任何内容,它只推送堆栈上的长度。使用此代码段获取表格长度:
lua_len(L, -1);
int count = luaL_checkinteger(L, -1);
lua_pop(L, 1);
lua_len
是在lua 5.2中获取表长度的正确函数,尽管它执行了不必要的元表检查。@peterm arrg他们必须去更改api:(所以annoying@greatwolf,谢谢你的帮助。我已经编辑了上面的代码,你能看一下吗?@Suge注意,可变长度数组是gcc的一个扩展,这就是为什么我在我的示例中使用vector
。我尝试使用int count=lua_-rawlen
,这很有效。我说得对吗?是的,它也有效。与lua_-rawlen
不同,lua_len
必须将其结果推送到堆栈上,因为它可能会触发\uu len
元方法,元方法可能会返回从nil
到userdata
的任何内容。感谢您的帮助。
int count = lua_rawlen(L, -1);
lua_len(L, -1);
int count = luaL_checkinteger(L, -1);
lua_pop(L, 1);