Lua:嵌套的if语句

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 块的标准方法是否存在?

点赞
用户582
用户582

我不确定这是否特别惯用,但您可以使用单个嵌套循环和 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
2012-09-12 10:49:28
用户1008957
用户1008957

在 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
2012-09-12 11:22:27
用户501459
用户501459

有时候,Lua 似乎缺少一些其他语言中习惯使用的非常方便的功能。

这是经济概念的权衡,这导致了实现的简化,进而导致了 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
2012-09-12 16:00:05
用户1542101
用户1542101

对于 {condition1,condition2,condition3} 中的每个元素 v,执行以下操作:

  • 如果 v() 为真,则执行核心逻辑。 ```

这样的写法可能适合您?

在 Lua 中,没有 nextcontinue 语句,但是它有类似的 ipairs 函数。

2012-09-12 23:59:09
用户6517623
用户6517623

解决方案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 Solution 1.将编译成更快的字节码。

2016-08-06 22:47:05