lua-users home
lua-l archive

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


I was thinking about the problem with the length operator again. As a follow up mail I would postulate, that not the length operator is the problem. There are many postings pointing to the manual where the length operator is correctly described with that strangeness, so it is not a bug:

The Lua manual describes the length function as follows:

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).

As described in the posting from Peter Cawley are tables by his definition simply arrays with holes.

The problem is the provided possibility of generating tables with holes. I do not see any indispensable advantage in making holes in arrays or lists or tables involuntary - is there any advantage? I do not even see a real application for holes in any array or in any list, say in any table by intention. Without holes most of the following Questions become obsolete:
Peter Cawley wrote:

First you need to see it as a problem, which I for one do not. ...
...
If you were to "fix" this "problem", how would you define the length
operator for tables?
1) Total number of keys in the table?
2) Total number of integer keys in the table?
3) Biggest integer key in the table? (and for tables with no integer keys?)
4) Smallest integer key in the table which is followed by a nil? (and
for tables with no integer keys?)
5) Something else?
Not to generate holes by chance means, that there should be a checker checking the consistency of a table and gives the user something like a hole warning. Preventing holes does not necessarily mean that it might not be allowed to begin a table with another number than 1. Important is a continuous content of a table. Functions may make it feasible to add elemenst on end or start of a table or to insert at a defined place. (I do not know how severe such an impact to the code may be.)

Another question is, if the allowance of holes by intention makes any indispensible benefit in using lua? I do not see any. At least it is to say that it is possible to write code without need for holes in arrays, as all other languages show. Vice verse one might say, that it is possible to write code despite holes in tables. The nasty behaviour of the length operator is without any alternative in the given state (see above). So I myself would see a hole-check and a safe length operator as a benefit for a coming Lua version.

Regards BB