2011-08-26 289 views
2

好了,所以我有一個奇怪的問題,下面Lua代碼:此代碼已運行奇怪表錯誤

function quantizeNumber(i, step) 
    local d = i/step 
    d = round(d, 0) 
    return d*step 
end 

bar = {1, 2, 3, 4, 5} 

local objects = {} 
local foo = #bar * 3 
for i=1, #foo do 
    objects[i] = bar[quantizeNumber(i, 3)] 
end 
print(#fontObjects) 

後,對象的長度應是15吧?但不,這是4.這是如何工作,我錯過了什麼?

謝謝Elliot Bonneville。

+0

我敢肯定,這是從一個較大的項目中提取的,但這裏有一堆錯誤。例如'#foo'不起作用,因爲'foo'不是一個表。 'fontObjects'沒有定義(我猜你的意思是'#objects')。 – BMitch

回答

5

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

但'酒吧'是五個元素長。正如我前面指出的那樣,我應該做1到15的for循環,15是bar * 3的長度。這不應該讓我有15件物品?爲什麼我得到4件物品? –

+0

@Elliot,我在回答這個問題時已經回答了這個問題。 HTH。 –

+0

好吧,我正在將我的陣列填充到第4項。爲什麼它不通過索引4?我期望輸出會像這樣:1,1,2,2,3,3,3,... 5,5,5。爲什麼不是這樣?我究竟做錯了什麼? –

0

功能quantizeNumber是錯誤的。你正在尋找的功能是math.fmod:

objects[i] = bar[math.fmod(i, 3)]