Yichz
Yichz

Reputation: 9671

Why length is different in Lua

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??

Upvotes: 3

Views: 459

Answers (1)

Yu Hao
Yu Hao

Reputation: 122383

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.

Upvotes: 4

Related Questions