是的,它是4
从Lua的参考手册:
表T的长度被定义为任何整数索引n,使得T [n]为不是nil和叔[n + 1]是零;而且,如果t [1]为零,则n可以为零。对于一个规则的数组,非零值从1到给定的n,它的长度恰好等于n,即它的最后一个值的索引。如果数组具有“空洞”(即其他非零值之间的零值),那么#t可以是任何直接在零值之前的指数(也就是说,它可以认为任何这样的零值作为结束的阵列)。
让我们修改代码,看看什么是表:
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个插槽。然而,参考手册中定义的#
运算符并不关心这一点。它只是寻找值不为零的索引,其后续索引为无。
在这种情况下,满足此条件的指数是4
这就是为什么答案是4。这只是方式Lua是。
零可以被看作代表数组的末尾。它有点像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
我敢肯定,这是从一个较大的项目中提取的,但这里有一堆错误。例如'#foo'不起作用,因为'foo'不是一个表。 'fontObjects'没有定义(我猜你的意思是'#objects')。 – BMitch