I have been dealing a lot with Lua in the past few months, and I really like most of the features but I'm still missing something among those:
- Why is there no
continue
? - What workarounds are there for it?
I have been dealing a lot with Lua in the past few months, and I really like most of the features but I'm still missing something among those:
continue
?I've never used Lua before, but I Googled it and came up with this:
Check question 1.26. I would conjecture it's also for the same reason that goto is hated in C.
The way that the language manages lexical scope creates issues with including both goto
and continue
. For example,
local a=0 repeat if f() then a=1 --change outer a end local a=f() -- inner a until a==0 -- test inner a
The declaration of local a
inside the loop body masks the outer variable named a
, and the scope of that local extends across the condition of the until
statement so the condition is testing the innermost a
.
If continue
existed, it would have to be restricted semantically to be only valid after all of the variables used in the condition have come into scope. This is a difficult condition to document to the user and enforce in the compiler. Various proposals around this issue have been discussed, including the simple answer of disallowing continue
with the repeat ... until
style of loop. So far, none have had a sufficiently compelling use case to get them included in the language.
The work around is generally to invert the condition that would cause a continue
to be executed, and collect the rest of the loop body under that condition. So, the following loop
-- not valid Lua 5.1 (or 5.2) for k,v in pairs(t) do if isstring(k) then continue end -- do something to t[k] when k is not a string end
could be written
-- valid Lua 5.1 (or 5.2) for k,v in pairs(t) do if not isstring(k) then -- do something to t[k] when k is not a string end end
It is clear enough, and usually not a burden unless you have a series of elaborate culls that control the loop operation.