Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump out of the outer loop if inner' for 'loop is executed in lua

Tags:

loops

lua

S = 'MSH, mdmOBX, TXA'
for u in string.gmatch(S, "([^,%s]+)"),1 do
    l[k] = u
    for a in string.gmatch(u,'.-([A-Z].*)'),1 do       
        g[z] = a
        print(g)
        _G["Map"..l[k]](Msg[g[z]],R[1])
    end
    _G["Map"..l[k]](Msg[l[k]],R[1])     
end

I have above code, I want statement outside of inner loop to be executed only if inner for loop is not executed, I tried using 'break' keyword but that did not work and control was passed to outerloop .how to fix this?

like image 618
S Khurana Avatar asked Apr 15 '14 17:04

S Khurana


2 Answers

Since Lua 5.2, you can just

goto label -- This statement goes to the jump-label label
::label:: -- The jump-label label

Using a flag variable which is checked after each loop which could set it for early bailout using successive break-statements is a classic of those fearing goto, or being condemned by lack of it.

local earlyreturn
for u in ... do
    for a in ... do
        if ... then
            earlyreturn = true
            break
        end
    end
    if earlyreturn then
        break
    end
end

Anyway, you could also wrap your loops in a function and use return.

function(...)
    for u in ... do
        for a in ... do
            if ... then
                return
            end
        end
    end
end(...)
like image 115
Deduplicator Avatar answered Oct 16 '22 17:10

Deduplicator


Technically, to answer the "how to break out multiple loops": you can use a goto statement with an appropriately placed label, although it may not be the best solution. How about wrapping the body of the inner loop in an if instead?

like image 4
The Paramagnetic Croissant Avatar answered Oct 16 '22 18:10

The Paramagnetic Croissant