3
有人可以解釋這種明顯的精神錯亂嗎?Lua的表長度運算符是如何工作的?
> t = {1, 2, 3} -- Table length 3. Simple
> = #t
3 -- Yep
> t[3] = nil -- Remove the last element?
> = #t
2 -- Ok it realises it is the last one (since #t = 3) and decrements the length
> t[6] = 6 -- Add a separate element?
> = #t
2 -- Ok... I guess? Although surely it knew #t = 2, and so now #t should be 6?
> t[4] = 4 -- Add another separate element
> = #t
4 -- Errr... what.
> t[5] = 5 -- Append another element
> = #t
6 -- Ok now it remembers element 6? Wtf?
好讓我再試一次...
> t = {1, 2, 3}
> = #t
3
> t[10] = 10
> = #t
3
> t[4] = 4
> = #t
4
> t[9] = 9
> = #t
4
> t[8] = 8
> = #t
10
什麼。
啊,這是解釋它。我不知道爲什麼他們不能爲未定義的情況返回nil或-1。 – Timmmm
您可以實現自己的'__len' metamethod來爲非序列表返回不同的結果,但是您仍然必須確定表是否是正確的序列。 – Adam