Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: nested if statements

Tags:

lua

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?

like image 654
nab Avatar asked Dec 06 '22 12:12

nab


2 Answers

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
like image 147
prapin Avatar answered Jan 12 '23 00:01

prapin


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
like image 28
Lily Ballard Avatar answered Jan 12 '23 00:01

Lily Ballard