是的,它是 4。
来自 Lua 参考手册:
表 t 的长度被定义为任意整数索引 n,使得 t[n] 不为 nil 且 t[n+1] 为 nil;此外,如果 t[1] 为 nil,则 n 可以为零。对于从 1 到给定 n 的非 nil 值的常规数组,它的长度正好是 n,它的最后一个值的索引。如果数组有“洞”(即,其他非 nil 值之间的 nil 值),那么 #t 可以是直接在 nil 值之前的任何索引(也就是说,它可以将任何这样的 nil 值视为结束数组)。
让我们修改一下代码,看看表里有什么:
local objects = {}
local foo = #bar * 3
for i=1, foo do
objects[i] = bar[quantizeNumber(i, 3)]
print("At " .. i .. " the value is " .. (objects[i] and objects[i] or "nil"))
end
print(objects)
print(#objects)
当你运行它时,你会看到 objects[4] 是 3 但 objects[5] 是 nil。这是输出:
$ lua quantize.lua
At 1 the value is nil
At 2 the value is 3
At 3 the value is 3
At 4 the value is 3
At 5 the value is nil
At 6 the value is nil
At 7 the value is nil
At 8 the value is nil
At 9 the value is nil
At 10 the value is nil
At 11 the value is nil
At 12 the value is nil
At 13 the value is nil
At 14 the value is nil
At 15 the value is nil
table: 0x1001065f0
4
确实,您填满了表格的 15 个位置。但是,参考手册中定义的表上的# 运算符并不关心这一点。它只是查找值不为 nil 的索引,并且其后面的索引 为 nil。
在这种情况下,满足这个条件的索引是4。
这就是为什么答案是 4。Lua 就是这样。
nil 可以看作是表示数组的结尾。这有点像在 C 中,字符数组中间的零字节实际上是字符串的结尾,而“字符串”只是它之前的那些字符。
如果您的意图是生成表 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,那么您将需要重写您的 quantize 函数,如下所示:
function quantizeNumber(i, step)
return math.ceil(i / step)
end