lua-users home
lua-l archive

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


To throw an alternative syntax in the pot: Labeling loops / blocks. This is how you can continue / exit outer loops in languages like Go or Java: Loops can be labeled with "<name>: <loop>" and continue/break take an optional name:

foo: for ... do
    while ... do
        continue foo
    end
end

bar: for ... do
    repeat
        break bar
    until ...
end


As I recall it, this is the right explanation for the current situation.

FWIW, I'd still like "break" to be improved to manage multi-level breaks, even as syntactic sugar for an hidden goto+label definition.
I don't despise GOTOs, but I think that using a goto to exit a multilevel loop is very error prone, especially if the label is far away from the goto, which is not so rare a case when algorithm with 3 or 4 nested loops are used (and this is really the case where you would find a multilevel break really useful).

Semantically a multilevel break is a very clear program action, which should be understandable at the break site ("I want to exit multiloop").
Using a goto at that same point must rely on "meta" information to convey the same meaning to the code reader, such as a comment or a descriptive label, but these may be misleading (possibly ambiguous: "goto start", to exit a multiloop).

I would welcome a syntax like "break 4", to exit four loop levels.
WRT the parser lookahead capabilities, maybe an uglier syntax could avoid excessive lookahead, like "break<4>". After all with Lua 5.4 and const/to-be-closed vars the syntax has already been uglified a lot, IMHO.

An alternative would be sort of like "relative jumps" (breaks are essentially that):

goto +1 = break (jumps just after the end of current loop body)
goto +2 = break 2 (jumps just after the end of the innermost enclosing loop body)

This could be generalized to implement a "continue" statement (multilevel too):

goto -1 = continue (jumps at the end of current loop body)
goto -2 = continue 2 (jumps at the end of the innermost enclosing loop)

(and maybe someone could come up with a syntax that's nicer than in these ramblings of mine :-).