问题
I have a question when I use # to calculte the length of a table. For Example:
local t = {"a", "b"}
local t1 = {"a", nil}
print(#t) -- 2
print(#t1) -- 1
local t = {"a", "b"}
local t1 = {nil, "a"}
print(#t) -- 2
print(#t1) -- 2
can someone tell me why it is?
回答1:
Unless __len metamethod is defined, # operator can only be operated on a table that is a sequence.
A sequence is, a table that, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n.
In your example:
local t = {"a", "b"}
t is a sequence that has a length of 2.
local t1 = {"a", nil}
is equivalent to local t1 = {"a"}, so t1 is a sequence that has a length of 1.
local t1 = {nil, "a"}
t1 is not a sequence, so #t1 is not defined.
来源:https://stackoverflow.com/questions/29248727/use-operator-to-calculate-the-length-of-a-table-in-lua