luacontinue

Lua goto statement to simulate continue raised error


Generally, my goal is to simulate the continue statement, which doesn't exist in Lua. I have read some thread about using goto to do this. I tried:

for i=0, 9, 1 do
    if i<5 then goto skip end
    print(i)
    ::skip::
end

It raised "lua: test.lua:2: '=' expected near 'skip'"

Is there any workaround to this? Thanks in advance


Solution

  • You can simulate continue (to a degree) using a combination of repeat .... until true and break (works with Lua 5.1+):

    for i=0, 9, 1 do repeat
        if i<5 then break end
        print(i)
    until true end
    

    Note that it makes break behave as continue, so you can't use it with its normal meaning. See this SO question for further details and alternative solutions.