lua-users home
lua-l archive

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


On Tue, 9 Jun 2015 22:58:56 -0500
Andrew Starks <...> wrote:
> 
> However, tables have two features that work if you have a sequence: the
> length operator will return the last integral index and ipairs will
> iterate, *in order* from 1 to max n.

In fact the length operator behafior is more complicated and unpredictable:
---------
Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> =#{1, 2, nil, 4, 0}
5
> =#{1, 2, nil, 4, 0, nil}
2
> =#{1, 2, nil, 4, nil, 0, nil}
2
> =#{1, 2, nil, 4, nil, nil, 0, nil}
4
>
---------


I cannot guess the exact rule for the length operator
as far as the only description of it in the manual is:

" 3.4.7 – The Length Operator
The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte). 

A program can modify the behavior of the length operator for any value but strings through the __len metamethod (see §2.4). 

Unless a __len metamethod is given, 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 non-negative 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. (So, there is no n such that the set {1..n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence. "


-- 
Mike