【发布时间】:2016-08-19 06:29:33
【问题描述】:
谁能解释这种明显的精神错乱?
> 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。
-
您可以实现自己的
__len元方法来为非序列表返回不同的结果,但您仍然需要确定表是否是正确的序列。