Lua - 表长度似乎无效

时间:2017-09-26 08:27:40

标签: lua lua-table

a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14

print(#a)

打印1

a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14
a[4] = 5

print(#a)

打印4

#操作符真正返回了什么?

1 个答案:

答案 0 :(得分:2)

如果表不是正确的序列,则应用于该表的#运算符的返回值是未定义的。

在您的两种情况下,a都不是正确的序列,因为a[2] == nila[3] ~= nil

#运算符返回正确序列的长度。