lua-users home
lua-l archive

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


Hi Lua experts,
I think this question should be in the FAQ, but it is not there yet.

[Q] Like many other languages Lua's "break" statement terminates only
the inner-most loop. How can one break out of a group of nested loops
(for, while, repeat...)

[A] One possibility to break out of any number of nested loops in one
shot is to wrap the code in an anonymous function and use "return"
statement to break out. See an example below:

--breaking from nested loops
t={ {0,1,2,3,4}, {10,11,-12,13,14} } -- two dimensional array

( function ()
   for i=1,#t do
     for j=1,#t[i] do
       if t[i][j]<0 then return end --break out of all loops if negative
       print( t[i][j] )
     end
   end
 end )() -- '()' call the anonymous function right away
-- End of code snippet

I found myself using this trick very often but I have no idea what
price in terms of performance and memory consumption it costs
(creating closures just for a single use, etc). Is it a good idiom and
are there any alternatives??

All suggestions and comments are highly welcome.
Thanks,
--Leo--