Logo

Programming-Idioms

History of Idiom 43 > diff from v33 to v34

Edit summary for version 34 by dromer:
[Lua] No goto necessary, works on more lua-variations.

Version 33

2016-09-23, 13:29:09

Version 34

2017-10-09, 15:51:56

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration

Idiom #43 Break outer loop

Look for a negative value v in 2D integer matrix m. Print it and stop searching.

Illustration
Code
for i,v1 in ipairs(m) do
   for j,v2 in ipairs(v1) do
      if v2 < 0 then
         print(v2)
         state = "found"
         goto outer
      end
   end
end
::outer::
Code
breakout = false
for i,v1 in ipairs(m) do
   for j,v2 in ipairs(v1) do
      if v2 < 0 then
         print(v2)
         state = "found"
         breakout = true
         break
      end
   end
   if breakout then break end
end
Comments bubble
you need at least Lua5.2.

using a function might be a better idea than using a goto,
as an example see http://www.programming-idioms.org/idiom/20/return-two-values/1661/lua
Comments bubble
1) First break breaks out of the inner-loop. Second break breaks out of the outer-loop.
2) Simplifying is possible. Change line 11 in if (state == "found") then break end and remove lines 1, 7 and 8.
3) No goto-statement.
4) As Nepta wrote: using a function might be another solution, as an example see http://www.programming-idioms.org/idiom/20/return-two-values/1661/lua