Lua的表长度运算符如何工作?

3
有人能解释这种明显的疯狂吗?
> 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

什么。

啊,是的,这解释了一切。我不知道为什么他们不能让#t在未定义的情况下返回nil或-1。 - Timmmm
你可以实现自己的__len元方法来返回非序列表的不同结果,但你仍然需要确定一个表是一个适当的序列还是不是。 - Adam
1个回答

5

Lua 手册解释了length运算符:

Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n. In that case, n is its length. Note that a table like

{10, 20, nil, 40}

is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接