1

In Lua is seems that if a single numeric key is missing from the table, the length still continues counting:

> print(#{[1]=1,[2]=2,[4]=4})
4

But this skipping two indices stops at the break

> print(#{[1]=1,[2]=2,[5]=5})
2

It's not just the unconvential constructor. Even if an skipped index is created after the creation of the table it still counts past it, so long the break is only one.

> x={1,2}
> print(#x)
2
> x[4]=4
> print(#x)

Is this an implementation error or is this how Lua supposed to work. Why is it like this? Any references to documentation of this would be interesting.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
DoubleMx2
  • 375
  • 1
  • 9

1 Answers1

3

This is how it works. The length of a table is only defined if the table is a sequence, with no holes. See http://www.lua.org/manual/5.2/manual.html#3.4.6 .

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks. I understand '#' is really only meant for sequential tables, and that this may be lua's excuse for this behavior, it just seems odd how it handles this '#' in non sequential tables. – DoubleMx2 Apr 20 '13 at 12:35