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();
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
所以我想知道是否有标准方法来避免ifLua中的嵌套块?
我不知道这是否特别惯用,但您可以使用单个嵌套循环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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3576 次 |
| 最近记录: |