Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Breaking loops "1 level up"?

Asked by
Link43758 175
10 years ago
local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
while wait(5) do -- loop a
    for i,v in pairs(table) do -- loop b
        print(v)
        if i == #table - 1 then
            -- break loop A?
        end
    end
end

Inside of loop B, I want to break loop A, which loop B is inside of. How would I go about doing this?

2 answers

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

Unfortunately, there's not a clean way to do this.

You would have to create some sort of flag that the upper levels use:

local breakA = false;
local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
while wait(5) do -- loop A
    for i,v in pairs(table) do -- loop B
        print(v)
        if i == #table - 1 then
            breakA = true; -- When we exit B, 
                -- it will break A
            break; -- Breaks out of B
        end
    end
    if breakA then
        break;
    end
end

You shouldn't require this sort of architecture frequently, however. Usually if you're running into this, there's a cleaner way to organize your code.

Ad
Log in to vote
0
Answered by
duckwit 1404 Moderation Voter
10 years ago

First of all, it's hard to tell what you are trying to achieve with this double loop structure, because even if you did "double break" from inside loop B, you could produce functionally identical results with just:

local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
for i,v in pairs(table) do
    print(v)
    if i == #table - 1 then break end --I think you'd want just #table, too, Lua table indices begin at 1 instead of 0
    end
end

But to answer your question (EDIT: As @BlueTaslem expresses), you'd need to flag a local boolean variable to indicate that a break was necessary:

local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
while wait(0.25) do -- loop a
    local b = false --break flag
    for i,v in pairs(table) do -- loop b
        print(v)    
        if i == #table - 1 then
            b = true
            break
        end
    end
    if b then break end
end

Answer this question