Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 558
Yichaoz Avatar asked May 04 '26 03:05

Yichaoz


1 Answers

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.

like image 175
Yu Hao Avatar answered May 06 '26 19:05

Yu Hao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!