听起来像是"让我谷歌给你"的问题,但不知怎的,我找不到答案.Lua #运算符仅使用整数键计数条目,因此table.getn:
tbl = {}
tbl["test"] = 47
tbl[1] = 48
print(#tbl, table.getn(tbl)) -- prints "1 1"
count = 0
for _ in pairs(tbl) do count = count + 1 end
print(count) -- prints "2"
Run Code Online (Sandbox Code Playgroud)
如何在不计算所有条目的情况下获取所有条目的数量?
我有从lua调用的ac函数.第一个参数是表.该表被滥用为底层api的数字输入数组.所以现在我的代码看起来像这样:
int n = 0;
lua_pushnil ( L );
while ( lua_next ( L, 2 ) ) {
n++;
lua_pop ( L, 1 );
}
int *flat = alloca ( n * 4 );
lua_pushnil ( L );
int i = 0;
while ( lua_next(L,2) ) {
flat[i++] = (int)lua_tonumber( L, -1 );
lua_pop ( L, 1 );
}
Run Code Online (Sandbox Code Playgroud)
我键入了代码盲,所以请原谅错误.也没有错误检查.但问题是我必须做两次while循环.有一种简单的方法可以避免这种情况吗?我想针对输入良好的情况进行优化 - 一个整数表.
lua ×2