[英]Am I right to read a nested lua table as argument from C function?
我将使用C语言实现一个函数,该函数将由Lua脚本调用。
这个函数应该接收一个lua表(甚至包含一个数组)作为参数,所以我应该阅读表中的字段。我尝试做如下操作,但是我的函数在运行时崩溃了。 谁能帮我找到问题?
/*
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;
}
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++)
{
colors[i] = luaL_checkinteger(L, -1-i);
}
此代码段看起来不正确(不必担心循环中缺少比较运算符)。 获取表长度的正确函数是lua_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 5.2, lua_objlen
替换为:
int count = lua_rawlen(L, -1);
如果要从表中移出很多元素,请确保堆栈上有足够的空间。 例如。 lua_checkstack
lua_len
不返回任何内容,它仅将长度推入堆栈。 使用此代码段获取表长度:
lua_len(L, -1);
int count = luaL_checkinteger(L, -1);
lua_pop(L, 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.