首页 > 解决方案 > 如果条件不满足,则在 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

标签: lua

解决方案


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

推荐阅读