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
?Lua, like most lanuages of this kind, has a "break" command that jumps out of the smallest enclosing loop. Normally you use "break" with "if" to decide when to exit the loop.
You use the break statement to finish a loop. This statement breaks the inner loop (for, repeat, or while) that contains it; it cannot be used outside a loop. After the break, the program continues running from the point immediately after the broken loop.
In Lua 5.2 the best workaround is to use goto:
-- prints odd numbers in [|1,10|]
for i=1,10 do
if i % 2 == 0 then goto continue end
print(i)
::continue::
end
This is supported in LuaJIT since version 2.0.1
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With