引子
环境 lua 5.2
a = {}
for i=1,2 do a[i] = i*3 end
a[4] = 11;
print(a[#a])
---print 11
-----------------------------------
a = {}
for i=1,3 do a[i] = i*3 end
a[5] = 11;
print(a[#a])
----print 9
---------------------------------
#a 第一个的值是4 第二个的值是3
依据我之前从书中看到的知识点来看的话 #a 第一个的值是2 第二个的值是3 才对啊
为啥呢
刚開始入门,源码部分就跳过吧,又没有合适的关键词搜索,仅仅能到大婶群里问了
一会儿 大神来了 给了个牛逼的解释
大婶:
2.5.5 – The Length Operator
The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is,
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil;
3.4.6 – The Length Operator
The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is,
A program can modify the behavior of the length operator for any value but strings through the __len metamethod
Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is,
{10, 20, nil, 40}
is not a sequence, because it has the key 4 but does not have the key 3.
从语言角度讲, lua 5.1 定义了 # 对数组取长度的约束. 而 lua 5.2 不严格定义了,仅仅说假设有 nil 就不确定
也就是说 lua 5.2 放宽了语言定义,同意实现更灵活
非常高深啊 我得慢慢啃
--[[高潮部分,直达G点]]
没什么高深的, lua 5.2 说,你有 nil 就别指望 #table 对