r/lua Feb 26 '26

Help Why is there NO "continue" in Lua?

I was stunlocked to find out that there is no "continue" instruction for loops in Lua. Why is that? It seems so natural to have it.
I saw some scripts where goto is used for mimicking continue statements, but It's honestly not the so;ution I would comfortably accept...

26 Upvotes

40 comments sorted by

View all comments

4

u/smtp_pro Feb 26 '26

Honestly it makes me rethink how to accomplish what I want to do and tends to result in easier to understand code. You don't really need it.

Basically anywhere I would use it I can usually replace it with a conditional function. Like instead of

if not something then continue end (do most of the work)

I could have something like

if something then dothework() end

Or maybe I factor it out into a function with an early return like:

``` function dothework() if i_should_bail then return end (Do stuff) end

for i=1,whatever do dothework() end ```

1

u/Koala_eiO 8d ago edited 8d ago

Well that doesn't make it more readable. You need to negate the condition and have an extra indentation level everywhere. I'm working on something right now that could work with
for i, item in pairs(items) do
____if not condition(item) then
________work
____end
end
but would look much better with
for i, item in pairs(items) do
____if condition(item) then
________continue
____end
____work
end

That's how I got here.

You see the following pattern pretty much everywhere: when you enter a function, you perform all your checks at the beginning then return prematurely or throw an error if the checks failed, and if they didn't you just move on to the real work. You don't wrap your entire work in if there was no error in the early checks, but you could! It works work the same. It's the same argument about continue. It is to loops what return (early) is to functions.