1

I have this simple while loop. I'd like to make it break the loop when the conditional variable is changed. Instead, it's finishing the loop and only then breaking it.

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
André Luís
  • 141
  • 2
  • 7
  • 3
    Unless I've missed something, isn't this a simple `break` statement: `if (false == a) break` (or something similar)? – Martin Oct 09 '19 at 12:59
  • In that case, would I have to repeat that condition before every action inside the loop? I mean, let's say I had functions that could change "a" value instead of those highlight commands. If in the first function "a" value is changed, it would not break the loop; it'd finish it before breaking. – André Luís Oct 09 '19 at 13:01
  • 2
    Yes indeed. Alternatively, you could do: `if (true == a) center_general_medium:highlight(1)` on each line – Martin Oct 09 '19 at 13:03
  • There is no other solution, right? – André Luís Oct 09 '19 at 13:05
  • Sounds like you want `continue` functionality, which is similar to a `break`. See https://stackoverflow.com/questions/3524970/why-does-lua-have-no-continue-statement – joehinkle11 Oct 09 '19 at 14:39

1 Answers1

4

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
DarkWiiPlayer
  • 6,871
  • 3
  • 23
  • 38