Explanation of borders in the manual

The explanation includes the limit case of maxinteger being a border.
It also avoids the term "natural", which might include large floats
with natural values.
This commit is contained in:
Roberto Ierusalimschy 2022-01-13 08:15:03 -03:00
parent 8dd2c912d2
commit 5d708c3f9c

View File

@ -1980,15 +1980,20 @@ character is one byte.)
The length operator applied on a table
returns a @x{border} in that table.
A @def{border} in a table @id{t} is any natural number
A @def{border} in a table @id{t} is any non-negative integer
that satisfies the following condition:
@verbatim{
(border == 0 or t[border] ~= nil) and t[border + 1] == nil
(border == 0 or t[border] ~= nil) and
(t[border + 1] == nil or border == math.maxinteger)
}
In words,
a border is any (natural) index present in the table
that is followed by an absent index
(or zero, when index 1 is absent).
a border is any positive integer index present in the table
that is followed by an absent index,
plus two limit cases:
zero, when index 1 is absent;
and the maximum value for an integer, when that index is present.
Note that keys that are not positive integers
do not interfere with borders.
A table with exactly one border is called a @def{sequence}.
For instance, the table @T{{10, 20, 30, 40, 50}} is a sequence,
@ -1997,12 +2002,9 @@ The table @T{{10, 20, 30, nil, 50}} has two borders (3 and 5),
and therefore it is not a sequence.
(The @nil at index 4 is called a @emphx{hole}.)
The table @T{{nil, 20, 30, nil, nil, 60, nil}}
has three borders (0, 3, and 6) and three holes
(at indices 1, 4, and 5),
has three borders (0, 3, and 6),
so it is not a sequence, too.
The table @T{{}} is a sequence with border 0.
Note that non-natural keys do not interfere
with whether a table is a sequence.
When @id{t} is a sequence,
@T{#t} returns its only border,
@ -2016,7 +2018,7 @@ the memory addresses of its non-numeric keys.)
The computation of the length of a table
has a guaranteed worst time of @M{O(log n)},
where @M{n} is the largest natural key in the table.
where @M{n} is the largest integer key in the table.
A program can modify the behavior of the length operator for
any value but strings through the @idx{__len} metamethod @see{metatable}.