Help with yielding a coroutine

Hello! this is related a bit too my last post, but I’m trying to stop a script without disabling it, I’ve come to using coroutine but I’m a bit confused on how to yield correctly, whenever I try it delivers no error but the script keeps running? (Note this is after coroutine.yield() has been used) The code is on a loop with a wait(timeperattack) between but how would I just end it mid wait(timeperattack))

you won’t be able to make it end during the wait()
I’d instead set a boolean to say something like “stop looping” after the wait and before any actions are done

depending on the case, you may want to use a bindableEvent, but the basic idea is this:

local continueLooping = true

-- infinite loop in thread until continueLooping=false
coroutine.wrap(function()
   while continueLooping do
      print("A")
      wait(1)
   end
end)()

wait(10)
continueLooping = false

this has the issue of having a delay for whatever is in the thread and after the loop ends, so I’d call a function to handle those actions immediately after setting continueLoop to false

Thank you, but this is what my script is already doing, the issue is just the mid wait() how would i do the function thing you described at the bottom

the function would pretty much be:

function endLoop()
   continueLooping = false
   print("B")
end

this way, B would print as soon as you want the loop to end, and A wouldnt print anymore

hmmm is there anyway to remove a thread? or stopping or removing?

you can’t do that from outside of the thread
after that loop ends and the function ends, the thread should be available to be garbage collected though

yeah thats what its currently doing, im just stuck because the code just runs with nil info and creates errors and lags.(Because its within the wait’s)

if there’s more than one wait(), then you can place an if statement to break the loop after each wait()

while continueLooping do
   print("A")
   wait(2)
   if not continueLooping then
      break
   end

   print("B")
   wait(2)
   if not continueLooping then
      break
   end

   print("C")
   wait(2)
end

also, I think repeat until is better for this than while

1 Like