Lua table 长度有问题?
Lua issue with table length?
我正在摆弄 Lua 表格,我注意到:
local t1 = {1, 5, nil, 10}
local t2 = {1, 5, nil, 10, nil}
print(t1[5], t2[5]) --> nil nil
print(#t1, #t2) --> 4 2
我原以为两个表的长度都是 4,但 t2
的长度结果是 2。有人能解释一下吗?
Frequently, in Lua, we assume that an array ends just before its first nil element. This convention has one drawback: We cannot have a nil inside an array. [...] But sometimes we must allow nils inside an array. In such cases, we need a method to keep an explicit size for an array.
我正在摆弄 Lua 表格,我注意到:
local t1 = {1, 5, nil, 10}
local t2 = {1, 5, nil, 10, nil}
print(t1[5], t2[5]) --> nil nil
print(#t1, #t2) --> 4 2
我原以为两个表的长度都是 4,但 t2
的长度结果是 2。有人能解释一下吗?
Frequently, in Lua, we assume that an array ends just before its first nil element. This convention has one drawback: We cannot have a nil inside an array. [...] But sometimes we must allow nils inside an array. In such cases, we need a method to keep an explicit size for an array.