lua-users home
lua-l archive

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


On Fri, 15 Aug 2014 13:37:41 -0300
Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:

> > I would thus conclude that my previously brought up argument in 3. a)
> > is valid, but only results in a slowdown of a factor of 1.33
> > (51.611 seconds versus 38.697 seconds).
> 
> If the goal is only to reduce calls to length, another option would be
> to modify ipairs so that it stops in the first nil entry with an index
> larger than #t. That would have some nice properties:
> 
> - The length operator would be called only for nil elements (plus one
> extra call at the end).
> 
> - It is more compatible with the original semantics of ipairs for
> regular tables. (If no metamethods, it stops in the first nil, which
> should be larger than #t in a proper sequence anyway.)
> 
> - It allows "unlimited" traversal, where you don't know the length
> beforehand (make #t == 0 so that it will stop at the first nil element).
> 
> -- Roberto
> 

It sounds like a "hack" to me.

Sometimes you don't know the length beforehand, but you might determine
it when necessary. Consider my previously brought up example of an SQL
database cursor (represented as userdata value). Here, ipairs could
start iterating through the result, even if the length is not
determined yet. Such a userdata could also support the # operator (for
those cases where the total length must be calculated beforehand).

If we assume that nil's are allowed as values, then calling the length
operator here (even if it's just for a few nil elements) would require
the underlaying SQL library to iterate through all result rows to
return a length.


I believe that __len should never be evaluated more often than
necessary.


Regards
Jan