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
11 years ago
1local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
2while wait(5) do -- loop a
3    for i,v in pairs(table) do -- loop b
4        print(v)
5        if i == #table - 1 then
6            -- break loop A?
7        end
8    end
9end

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
11 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:

01local breakA = false;
02local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
03while wait(5) do -- loop A
04    for i,v in pairs(table) do -- loop B
05        print(v)
06        if i == #table - 1 then
07            breakA = true; -- When we exit B,
08                -- it will break A
09            break; -- Breaks out of B
10        end
11    end
12    if breakA then
13        break;
14    end
15end

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
11 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:

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

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:

01local table = {"hi!", "how", "are", "you", "doing", "on", "this", "fine", "day?"};
02while wait(0.25) do -- loop a
03    local b = false --break flag
04    for i,v in pairs(table) do -- loop b
05        print(v)   
06        if i == #table - 1 then
07            b = true
08            break
09        end
10    end
11    if b then break end
12end

Answer this question