3

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user1723404
  • 29
  • 1
  • 5

1 Answers1

3

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • local t1 = {nil, "a"} t1 is not a sequence, dose it mean that #t1 returns a wrong length. – user1723404 Mar 25 '15 at 09:05
  • @user1723404 There is no agreed on "right" length for a table that is not a sequence. In practice, for a non-sequence, Lua might return different results for tables that have the same entries. For example, if you test `local t1 = {nil, "a"}; print(#t1)` you will probably get `2`. But if you test `local t1={}; t[1]=nil; t[2]="a"; print(#t1)` you will probably get `0`. – tehtmi Mar 25 '15 at 10:50
  • @user1723404 `#t1` is not defined, means there's no *correct* value of it. In particular, it's possible that you get different value in different Lua implementations. – Yu Hao Mar 25 '15 at 11:13