lua - 如果条件不满足,则在 Lua 上中断 while 循环
问题描述
我有这个简单的while循环。我想让它在条件变量改变时打破循环。相反,它完成了循环,然后才打破它。
a = true
while( a == true )
do
center_general_medium:highlight(1)
center_general_small:highlight(1)
center_general_tiny:highlight(1)
a = false << ------------------- should break loop here if, for some reason, "a" value is changed.
center_general_medium:highlight(1)
center_general_small:highlight(1)
center_general_tiny:highlight(1)
end
解决方案
Short answer: no, that's just not how loops work.
Long answer: Technically, you could do this with lots of magic, but it wouldn't look pretty. Coroutines and metamethods can take you a long way, if you're willing to put some work into it, but I don't think it's worth it in your example.
Looking at your problem, it's obvious that you actually have an inner and an outer loop; the outer one being the while
loop, and the inner just looping over a few objects and calling :highlight(1)
on them. So what you really want, is to break
through two loops at once, which can't be done. Instead, you should write the inner loop as an actual loop, and break out of that when a == false
, then let the outer loop stop because of the unmet condition.
local objects = {
center_general_medium,
center_general_small,
center_general_tiny,
center_general_medium,
center_general_small,
center_general_tiny
}
a = true
while a do
for _, object in ipairs(objects) do
object:highlight(1)
if not a then break end
end
end
推荐阅读
- c# - 在实体框架中来自父类的属性上使用 [NotMapped]
- android - React Native 重命名现有项目
- codeigniter - 如何访问我的任何控制器中的一个控制器实例?
- graphql - GraphQL查询访问数组中的第一项?
- ios - Swift - AVCaptureSession,如何捕获输出
- vba - 如何用 powerapps 中 Combobox 值的变量提取替换请求日期
- android - 有没有办法循环 URL 以在 android studio 中获取 JSON 数据?
- mysql - 使用 sql 查询将文件移动到另一个目录
- c# - 如何使用 HttpClient C# 下载多个文件?
- javascript - .map() 将错误的值映射到我的标题标签