Lua:嵌套的if语句
2012-11-3 10:37:2
收藏:0
阅读:171
评论:5
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
因此,我想知道在Lua中避免嵌套 if 块的标准方法是否存在?
点赞
用户1008957
在 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
2012-09-12 11:22:27
用户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
对于 {condition1,condition2,condition3} 中的每个元素 v,执行以下操作:
- 如果
v()为真,则执行核心逻辑。 ```
这样的写法可能适合您?
在 Lua 中,没有 next 或 continue 语句,但是它有类似的 ipairs 函数。
2012-09-12 23:59:09
用户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
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
我不确定这是否特别惯用,但您可以使用单个嵌套循环和
break来模拟continuefor 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