Having trouble breaking a for loop

So I have this repeat loop and keep in mind I want these for loops to run forever while the repeat loop is running but anyway I’m trying to break the second for loop but its not working, I’m trying to make the variable (Needkills) to go down -1 everytime a zombie died

2 Likes

you can easily ‘break down’ a for loop by placing an if statement around everything that’s inside of it, for example like so:

local condition = true

for i, v in pairs(table) do
   if condition then
      -- insides of the for loop here
   end
end



-- once you want to break it, just do:
condition = false
-- and it won't do anything anymore
1 Like

oh okay im gonna go try that rn

the zombie died function can be very glitchy as there aren’t any condition that it will count the same one again

also you can use spawn(function() end) in order to keep resumed threads running and make a new one that doesn’t interrupt

Are you talking about what i have can be very glitchy?

yeah, you have to add some statement to make sure if it’s not the same dead zombie you counted or by inserting it into a new table then filtering the ones in that table

ohhh okay yea im gonna have to make sure its not the same zombie

But I need the for loop to be able to run again tho

Then you can just set the condition variable to true again

oh so should I set it true after i set it false?

set it to false when you want to break it, then you can set it to true once you want to use it again

ok now im have trouble of where i should set it back to true i tried putting it in the for loop and in the repear loop

Your issue is probably that by the time you set it to true, the loop hasn’t paused but has just run through the remaining things quickly and finished, you can wrap it into a coroutine and add the following instead of the if statement at the top:

local condition = true

coroutine.wrap(function()

   for i, v in pairs(table) do
      while not condition do
         wait()
      end
      -- for loop insides here
   end

end)()

okay imma try that, I haven’t really learned about the coroutine so I’m little confused on what it is

1 Like

coroutine allows the things inside the coroutine run while the rest of the script already continues without waiting for the while loop in this case

oh that sounds usefull, so do i replace my repeat loop with the coroutine.wrap(function()?

You can use a break statement to break an entire iteration loop (the entire while/for/repeat loop) or alternatively you can use a continue statement to skip the current iteration cycle and continue with the execution of the next iteration cycle (a single pass/cycle of an entire while/for/repeat loop).

yea but what im tryning do is break the for loop but let it still run inside the repeat loop

You mean let the repeat loop run even after the for loop is terminated?

yeah that is what I meant to say