Lua:嵌套的if语句

  • 本文关键字:if 语句 嵌套 Lua lua
  • 更新时间 :
  • 英文 :


Lua是一种轻便而强大的语言,但有时它感觉缺少一些我们在其他语言中习惯的非常方便的功能。我的问题是关于嵌套的if条件。在Perl、Python和C++中,我通常倾向于避免嵌套结构,并尽可能编写纯代码,如:

# 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缺少nextcontinue语句,因此相同的代码看起来像:

-- 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

所以我想知道是否有标准的方法可以避免Lua中嵌套的if块?

在Lua 5.2上,您可以使用goto语句(请小心)!

该关键字的典型用法之一是替换缺失的continuenext语句。

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

我不知道这是否特别惯用,但您可以使用单个嵌套循环和break来模拟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

有时感觉缺少一些我们在其他语言中习惯的非常方便的功能

权衡是概念的经济性,这导致了实现的简单性,这反过来又导致了Lua著名的速度和小尺寸。

至于您的代码,这不是最广泛的解决方案(请参阅其他受访者了解实现continue的两种方法),但对于您的特定代码,我只想写:

for i = 1, 5 do
    if  some_condition_1() 
    and some_condition_2() 
    and some_condition_3() then
        the_core_logic_goes_here()
    end
end
for v in pairs{condition1,condition2,condition3} do
    if  v() then
        the_core_logic_goes_here()
    end
end

可能是你喜欢的?

"Lua缺少下一个或继续语句"Lua作为下一个语句和一个非常相似的函数"ipairs"。

解决方案1

您可以将所有条件添加到if语句中,然后使用else语句,这是您应该做的

if cond_1() and cond_2() and cond_n() then
  the_core_logic_goes_here()
else
  -- do something else here
end

解决方案2

你可以使用类似的东西,但看起来更像你更熟悉的其他语言,那就是做if cond_n() then else return end,如果不满足cond_n(),它只会返回零。总之,它应该看起来像这样:

for idx=1, 5 do
  if cond_1() then else return end
  if cond_2() then else return end
  if cond_3() then else return end
  if cond_4() then else return end
  the_core_logic_goes_here()
end

然而,我真的认为你应该使用前者,这是一个更好的解决方案,我很确定lua解决方案1。将编译成更快的字节码。

最新更新