lua-users home
lua-l archive

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


On 14/06/2011 6.06, Xavier Wang wrote:


2011/6/14 Lorenzo Donati <lorenzodonatibz@interfree.it
<mailto:lorenzodonatibz@interfree.it>>

    On 14/06/2011 5.41, Xavier Wang wrote:

        And you will find in Lua 5.2 beta, the meaning of # operator is
        changed.


    Really? I thought only the description in the manual was changed,
    supposedly to be clearer.

    Or do you mean the fact that now # respect the __len metamethod?

    Am I missing something?

in beta:
The length of a table |t| is only defined if the table is a /sequence/,
that is, all its numeric keys comprise the set /{1..n}/ for some integer
/n/. In that case, /n/ is its length. Note that a table like

in 5.1.4:

The length of a table |t| is defined to be any integer index |n| such
that |t[n]| is not *nil* and |t[n+1]| is *nil*; moreover, if |t[1]| is
*nil*, |n| can be zero. For a regular array, with non-nil values from 1
to a given |n|, its length is exactly that |n|, the index of its last
value. If the array has "holes" (that is, *nil* values between other
non-nil values), then |#t| can be any of the indices that directly
precedes a *nil* value (that is, it may consider any such *nil* value as
the end of the array).


it means: this table:

local t = {1, 2, nil, 4}

in lua5.1.4, #t will be 2 or 4, but in lua5.2, #t is undefined.



Ouch. I assumed that to mean that the _concept_ of "length" is undefined, not what # returns. But maybe I assumed too much.

I think some people won't be happy if what you say is true. IIRC some people found a useful use for the behaviour of # when a table has holes in 5.1.4 (filling unfilled slots or the like, I don't remember well).

If you interpretation is right (as it could be), if a table t has holes, i.e. it is not a sequence in the new jargon, #t may well return nil or whatever it likes.

If this is true, I think it should be pointed out among the incompatibilities at the end of the manual.