lua-users home
lua-l archive

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


Roberto wrote:

> O.k. there is a problem, maybe we have to say we don't know a solution,
> maybe sometime later we can come up with something,
>
>              BUT NOW LETS LIVE WITH IT.
>
> PS: to anyone wanting to propose a solution: Please, first read
> everything that was written in the past.

Well, I have read everything since December 2010, I think.

Axel wrote:
>
> My suggestion back then was, and I still haven't seen a good refute
> of, remove any default meaning of #. # is what __len says it is. And
> if you want it to behave like it is now, set __len to table.edge or
> better array.edge. So no one is ever going to be surprised, and if
> __len is not set, it throws an error.
>

Making the default __len a first-class object with its own name in
the table library?  An excellent idea, for which I suggest the
following extension of the present default __len:

~~~~
* table.edge(tbl[,k])

Returns the first at most k edges in tbl, where an edge is a
non-negative integer n such that tbl[n] is not nil but tbl[n+1] is
nil, except that 0 is an edge when tbl[1] is nil no matter what tbl[0]
is.  edge(tbl,-k) returns the last at most k edges.  In particular,
edge(tbl,-1) returns the largest positive integer index in the table,
or 0 if the table is empty.

edge(tbl,0) returns one arbitrarily chosen edge.  Which edge this
will be is undefined except when there is only one edge, i.e. the
table is empty or a proper sequence, in which case edge(tbl) returns
the number of elements in the sequence.

The default value of k is 0.
~~~~

I.e.

     t={nil,2,3,nil,5,6,7,8,nil,10,[30]=30}
     table.edge(t,1)   --> 0
     table.edge(t,100) --> 0,3,8,10,30
     table.edge(t,-1)  --> 30
     table.edge(t,0)   --> 10 -- for Lua 5.2 on my laptop

During the discussion of the length operator, one could simply say that
by default, #tbl returns table.edge(tbl), and that only in the case of
sequences does this correspond to the intuitive notion of length.

But the other part of your suggestion, i.e. forcing every Lua user to choose
between:

   1. Requiring Microlight and using Array (which would set __len);
   2. Setting a metatable yourself;
   3. Not using #t.

is going too far.  You can do it to the programmers who work for
you.  You can't do it to Patrick Henry or Nelson Mandela.