lua-users home
lua-l archive

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


Luis Carvalho wrote:

You can also use a 'do' block:

--breaking from nested loops
t={ {0,1,2,3,4}, {10,11,-12,13,14} } -- two dimensional array
do
 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(i,j,t[i][j])
   end
 end
end

But return only returns from the current function -- it
doesn't care about do blocks:

 > do
 >>   for i = 1, 10 do
 >>     for j = 1, 10 do
 >>       print("Returning")
 >>       return
 >>     end
 >>   end
 >> end; print("Not reached!")
 Returning
 >

As far as the original question, if the inner loop doesn't
naturally fit into its own (named) function, I usually do
something like this:

 do -- So that it'll work interactively.
   local t = {{0, 1 ,2 , 3, 4}, {10, 11, -12, 13, 14}}

   local i, loop = 1, true
   while i <= #t and loop do
     for j = 1, #t[i] do
       if t[i][j] < 0 then
         loop = false -- End the outer loop.
         break -- BREAK OUT OF THE INNER LOOP.
       end
       print(t[i][j])
     end
     i = i + 1
   end
 end

--
Aaron