是的,它是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