使用C API在Lua中创建一个带有表键的表格。

在 Lua 中,您可以创建一个其键本身为表的表:

t = {}
t[{1,2}] = 2

我想知道如何使用 C API 进行类似的操作。也就是说,我正在编写一个可以从 Lua 中调用的 C 函数,它将返回一个具有表键的表。我尝试推送一个表作为键,然后使用 lua_settable,但似乎什么都没有发生。

编辑:相关代码:

lua_createtable(L, 0, n);
for(i = 0; i < n; ++i){
    // push the key table
    lua_createtable(L, 2, 0);
    for(j = 0; j < 2; ++j){
         lua_pushinteger(L, j+1);
         lua_pushinteger(L, j);
         lua_settable(L, -3);
     }
     // push the value table
     lua_createtable(L, 4, 0);
     for(j = 0; j < 4; ++j){
         lua_pushinteger(L, j+1);
         lua_pushnumber(L, j);
         lua_settable(L, -3);
     }
     lua_settable(L, -3);
}

编辑: 我傻了;我在最后使用了 lua_objlen(L, -1) 检查表的大小,因为没有整数键入口,所以返回值为 0。此外,在处理表的 Lua 代码中,我使用了ipairs而不是pairs。愚蠢的错误。

原文链接 https://stackoverflow.com/questions/3322393

点赞
stackoverflow用户298661
stackoverflow用户298661

使用表作为键,然后使用lua_settable是正确的方式。很可能,您只是忘记了同时推送一个值,实际上是 t = { {} = nil },这当然是无意义的。


Pushing a table as the key and using lua\_settable is the right thing to do. Most likely, you just forgot to also push on a value and did effectively t = { {} = nil }, which is of course nothing.
2010-07-23 21:35:33
stackoverflow用户171187
stackoverflow用户171187

我检查表格输入的方法错了。我已经编辑了问题并附上解决方案。

2010-07-23 21:55:53