问题
I'm learning Lua for corona sdk and I have these
local type1 = {nil, "(", nil, "x" ,nil , ")" ; n=6}
local type2 = {"(",nil, "x",nil, ")",nil ; n=6}
print(#type1) --prints 6
print(#type2) --prints 3
why the second one is not 6 too??
回答1:
The # operator doesn't work on every table, it works only on a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some integer n. In that case, n is its length. For instance, local t = {"hello", 42, true} is a sequence.
But both your tables are not sequence because they have "holes" of nil.
See Lua 5.2 Reference Manual: The length operator.
来源:https://stackoverflow.com/questions/22059329/why-length-is-different-in-lua