Lua:嵌套的 if 语句

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

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

最佳答案

在 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

关于Lua:嵌套的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12386085/

相关文章:

c++ - 用于 Boost 数组的 SWIG/Lua 类型映射

lua - 为 lua/torch 安装 hdf5、mattorch/matio

c - Lua (LuaJit) 和 C 中的对象生命周期

c - Lua 中是否有等效的 scanf 函数?

variables - 函数/变量作用域(按值传递还是引用传递?)

vim - 如何封装Lua/Python/Ruby编写的Vim插件代码?

Lua 相当于 Python 的 Multiprocessing?

visual-c++ - 从另一个线程调用 lua 函数(作为回调)是否足够安全?

regex - Lua 中使用 .gsub() 的正则表达式

C++ 编译器错误递归模板