2

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

RazorVE
  • 57
  • 7

2 Answers2

7

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
1

The goto statement is not supported by Lua 5.1 (and older) as well as not by LuaJIT which I consider real issue. Following code wraps the code which is subject to continue statement into an anonymous function - which I consider better readable but also your original iteration code remains almost unchanged.


for i = 0, 9, 1 do
  (function()
     if i < 5 then return end
     print(i)
  end)()
end

stancikcom
  • 74
  • 3
  • 1
    Your answer does not address the question posed by the author. The question is about an equivalent of the `continue` statement, but your code effectively performs a `break` when the `if` succeeds. – Siphalor Apr 07 '22 at 18:19
  • Correctly, the anonymous function should encapsulate only the code which is subject to `continue` statement – stancikcom Apr 09 '22 at 08:39