lua-users home
lua-l archive

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




Am 13.09.2016 um 11:37 schrieb Malma:

I think this explanation must be in official doc if it's a source of confusion.

print(# {[1] = 10, [2] = 20, [3] = nil, [4] = nil, [5] = 40} ) -- is not sequence ? print(# {10, 20, nil, nil, 40} ) -- is sequence ? From doc: Note that a table like {10, 20, nil, 40} is not a sequence...

output:

2
5

The # operator computes the number of elements of a sequence in a Lua table
# returns a valid result only for sequences.

A Lua table contains a sequence if and only if all integer keys greater zero are contiguous; i.e. there must be no missing numbers.

If there are gaps, the table contains no sequence.

Th table may contains values for other keys, including 0, negative, or non-integer numbers, this does not affect the sequence.

Note that this definition is completely independent of the implementation detail has part / array part; one does not need to care about that.
It's only about integer keys.

nil can't be stored in a table. Assigning nil to a table key removes the key. Use another value to tag special (e.g.missing) entries, like false

{10, 20, nil, nil, 40} contains NOT a sequence
{10, 20, false false, 40] contains a sequence
{ [0]="null", 10, 20, 30, a="alpha",  [math.pi] = "pi" } contains a sequence

--
Oliver