Tim*_*mmm 3 lua luajit lua-table
有人可以解释这种明显的疯狂吗?
> 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
什么.
仅当表是正确的序列(连续的整数键)时,才定义表的长度.
Lua 手册解释了长度运算符:
除非给出__len元方法,否则仅在表是序列时定义表t的长度,即,对于某些非负整数n,其正数字键的集合等于{1..n}.在这种情况下,n是它的长度.注意表格就好
Run Code Online (Sandbox Code Playgroud){10, 20, nil, 40}不是序列,因为它具有键4但没有键3.(因此,没有n使得集合{1..n}等于该表的正数字键集.)但请注意,非数字键不会干扰表是否为序列.