lua-users home
lua-l archive

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

On Wed, 1 Sep 1999, David Jeske wrote:

> I'm not concerned with whether the solution involves adding a break
> statement or not. However, I have to second Fred's complaint about
> "while()" being the only available looping structure. 

Here's another possibility that wouldn't require extending the language at
all.  If you add a tail-recursion optimization, you could make a loop look
like this:

local Loop = function( i )
  [ loop code ]
  if( i == %endvalue ) then
  [ more loop code ]
  Loop( i + %increment )
Loop( startvalue )

That would give me everything I'd need.  It would also make setting the
initial value for the loop index and incrementing the loop index be in
standard locations.  That might make reading code a bit easier.  

I disagree, by the way, that putting a "break" in the middle of a loop
creates large numbers of infinite loops.  In Lua, essentially all of the
infinite loops that I write are because I forgot to write the loop
index increment code.  (ie: "i = i + 1" or whatever.)  Tail recursion
would make that much less likely, since in order to make it loop at all
you'd have to write what should be the loop increment code.

I would think that tail recursion is a fairly simple optimization to add,
too.  You just have to check to see if any local variables are used after
the recursion call and, if not, clean up the stack before making the
function call.