Lua is a light and powerful language, but sometimes it feels like lacking some very convenient features we get used to in other languages. My question is about nested if
conditions. In Perl, Python, C++ I generally tend to avoid nested constructions and write plain code whenever possible like:
# Perl:
for (my $i = 0; $i < 10; ++$i) {
next unless some_condition_1();
next unless some_condition_2();
next unless some_condition_3();
....
the_core_logic_goes_here();
}
Lua is missing that next
or continue
statement, so the same code will look like:
-- Lua:
for i = 1, 5 do
if some_condition_1() then
if some_condition_2() then
if some_condition_3() then
the_core_logic_goes_here()
end
end
end
end
So I'm wondering if there's standard approach to avoid nested if
blocks in Lua?
On Lua 5.2, you can use the goto statement (with care please)!
One of the typical usage for that keyword is to replace the missing continue
or next
statement.
for i = 1, 5 do
if not some_condition_1() then goto continue end
if not some_condition_2() then goto continue end
if not some_condition_3() then goto continue end
the_core_logic_goes_here()
::continue::
end
I don't know if this is particularly idiomatic, but you could use a single nested loop along with break
to simulate continue
for i = 1, 5 do
repeat
if some_condition_1() then break end
if some_condition_2() then break end
if some_condition_3() then break end
the_core_logic_goes_here()
until true
end
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