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 缺少那个
next
或 continue
语句,因此相同的代码将如下所示:-- 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声明(请小心)!
该关键字的典型用法之一是替换缺少的 continue
或 next
陈述。
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/