lua-users home
lua-l archive

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

On Jan 14, 2010, at 5:07 PM, Doug Rogers wrote:
> Klaus Ripke wrote:
>> On Sat, Jan 09, 2010 at 12:52:33PM +0300, Alexander Gladysh wrote:
>>> On Sat, Jan 9, 2010 at 12:37, steve donovan <> wrote:
>>>> 2010/1/9 Ignacio Burgueño <>:
>>>>>> 17. Documented behaviour of ipairs() is changed from "iterates until
>>>>>> *first nil*" to "traverses table length elements as defined by length
>>>>>> operator".
>> I fail to see how breaking perfectly valid code
>> by trading a well defined behaviour for all tables
>> for something undefined on "arrays with holes" does any good.
> Agreed. The only reason #t has its undefined behavior is because it is
> impractical for it to iterate the table. But the whole point of ipairs()
> is to iterate the table - it is already doing that! So I prefer the
> previous behavior - iterate until nil.
> Now if there were a clever way to modify the length operator so that the
> two methods were the same, that would be the ultimate solution. I can't
> see any easy method, though. The best one I have come up with is to keep
> upper and lower bounds on #t as nils are set and unset, then
> recalculating the length on the next #t usage. It can be made to work,
> but the expense is too high. #t is intended for normal arrays (or for
> LPEG, or for vector magnitudes, or... that's another thread entirely!).

ipairs could be modified to take parameters akin to unpack.

	ipairs( t )	-- iterate t until you hit a nil entry
	ipairs( t, lo ) -- iterate t starting at lo until you hit a nil entry
	ipairs( t, lo, hi ) -- iterate from lo to hi returning i, t[ i ]
	ipairs( t, lo, hi, step ) -- iterate from lo to hi via step returing the i, t[ i ]

Then the new behavior is represented as ipairs( t, 1, #t ). Note, however, that this is different from the definition of unpack since it stops at nils while unpack always iterates until #t.

This change would have a cost in the logic for ipairs, but should be free in the loop iteration.

On the other hand, if you know the bounds or are prepared to calculate them, "for i = lo, hi" is, I believe, more efficient.