pairs & ipairs as first-class loops

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

pairs & ipairs as first-class loops

Stuart P. Bentley
As the discussion of loops seems to have gone prematurely cold since the  
un-deprecation of ipairs, I figure I'd resurface one of the ideas that had  
been roughly proposed in the discussion: making table traversal loops part  
of the core language, rather than just iterator functions.

One type of loop would visit every key in a table once, operating  
similarly to pairs():

   for k, v over t do
     -- code...
   end

would be equivalent to

   do
     local k, v
     k = next(t)
     while k do
       v = t[k]
       -- code...
       k=next(t,k)
     end
   end

The other new type of loop would iterate from 1 to the first hole in the  
table, conceptually similar to ipairs():

   for i, v thru t do
     -- code...
   end

would be equivalent to

   do
     local i, v
     i = 1
     while t[i] do
       v = t[i]
       -- code...
       i=i+1
     end
   end

The generic for would remain for other iterators, such as io.lines().

The advantages of this:
* Reduced overhead, likely leading to increased performance
* Simpler execution for the two most common loops
* Two less standard functions in the global namespace

The disadvantages:
* Two more forms of the "for" loop

Reply | Threaded
Open this post in threaded view
|

Re: pairs & ipairs as first-class loops

Joshua Jensen
  ----- Original Message -----
From: Stuart P. Bentley
Date: 8/17/2010 8:32 AM

> As the discussion of loops seems to have gone prematurely cold since
> the un-deprecation of ipairs, I figure I'd resurface one of the ideas
> that had been roughly proposed in the discussion: making table
> traversal loops part of the core language, rather than just iterator
> functions.
>
> One type of loop would visit every key in a table once, operating
> similarly to pairs():
>
>   for k, v over t do
>     -- code...
>   end
>
> The other new type of loop would iterate from 1 to the first hole in
> the table, conceptually similar to ipairs():
>
>   for i, v thru t do
>     -- code...
>   end
>
> The advantages of this:
> * Reduced overhead, likely leading to increased performance
> * Simpler execution for the two most common loops
> * Two less standard functions in the global namespace
>
> The disadvantages:
> * Two more forms of the "for" loop
Syntax aside (I'm impartial), I am very much for this, especially for
the optimizations that can be had.

Josh