lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 16 April 2012 09:31,  <csrl@gmx.com> wrote:
> Hello,
>
> I'm trying to reconcile documentation to the surprising behavior of the length operator on a table.
>
> Please refer to http://www.lua.org/manual/5.2/manual.html#3.4.6
>

For reference, that documentation (snipped) says:

"
    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. In that case, n is its length. Note that a table like

      {10, 20, nil, 40}
    is not a sequence, because it has the key 4 but does not have the
    key 3.
"

> My point in this is that if #t returns a particular value n, it becomes surprising if each key of {1..n} does not index a non nil value in the table.

It might be surprising, until you read the documentation.

> But in any case, I'd expect defined behavior rather than undefined behavior.  I can not wrap my head around how the above behavior might be defined.

Re-read the first sentence of the documentation you linked, especially
the words "is only defined if". The documentation clearly says that
the length of non-sequence tables is *not* defined. That means you
cannot rely on it to give any particular value. It's not defined to be
random either though, so don't use it for a random number generator :)

Dirk is right, this issue has been brought up many times - if you're
interested in the background, reading the mailing list archives should
be fairly educational. I answered your post in full mainly because
it's the first question I've seen about 5.2 in particular, where the
documentation was actually (hopefully!) clarified about this exact
point based on all the discussions that have taken place about the
same behaviour in 5.1.

Regards,
Matthew