Search code examples
luaindiceslua-table

Length of a sequential table in Lua may skip indices?


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.


Solution

  • 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 .