Why does Lua's length (#) operator return unexpected values?
Solution 1:
Quoting the Lua 5.2 Reference manual:
the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some integer n
The result of #
operator on non-sequences is undefined.
But what happens in C implementation of Lua when we call #
on a non-sequence?
Background: Tables in Lua are internally divided into array part and hash part. That's an optimization. Lua tries to avoid allocating memory often, so it pre allocates for the next power of two. That's another optimization.
- When the last item in the array part is
nil
, the result of#
is the length of the shortest valid sequence found by binsearching the array part for the first nil-followed key. - When the last item in the array part is not
nil
AND the hash part is empty, the result of#
is the physical length of the array part. - When the last item in the array part is not
nil
AND the hash part is NOT empty, the result of#
is the length of the shortest valid sequence found by binsearching the hash part for for the first nil-followed key (that is such positive integeri
thatt[i] ~= nil
andt[i+1] == nil
), assuming that the array part is full of non-nils(!).
So the result of #
is almost always the (desired) length of the shortest valid sequence, unless the last element in the array part representing a non-sequence is non-nil. Then, the result is bigger than desired.
Why is that? It seems like yet another optimization (for power-of-two sized arrays). The complexity of #
on such tables is O(1)
, while other variants are O(log(n))
.