Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Remotely Terminating Threads?

I'm using coroutines with loops in them, and I want to remotely terminate a coroutine while it's running. What I mean by that is I want to stop it completely outside of that thread, meaning I can't use something like coroutine.yield or a conditional in the running coroutine. Any help? The only solution I can think of is using a seperate script to emulate a coroutine, and destroy that script when I want the thread to stop. This seems ineffecient and messy though. Any ideas or links are appreciated, thanks!

2 answers

✓ Accepted answer

You cannot do this, because this is not in the spirit of threads, and it's definitely not in the spirit of cooperative execution, which is what coroutines are.

A coroutine has to choose to stop itself. This is because it's not necessarily clear where it's "OK" to stop -- what if it is half-way done with something important, and stopping it there will break everything?

It needs to choose to stop itself -- however, you can make it consult some flag that other scripts can command that will make it choose to stop:

function launch(stopper)
	spawn(function()
		repeat
			wait()
			print(math.random())
		until stopper.stop
	end)
end


s = {}
launch(s)

wait(5)
s.stop = true

The above creates a background loop that goes until stop is set on its argument, which is done after 5 seconds pass.

2 comments

0

I already knew about this method, but it doesn't really work fro what I'm trying to accomplish. Thanks anyways.

0

I was dumber when I posted this lmao

Coroutines will stop if the loop finishes. So create a variable outside of the coroutine function and change it to complete the loop.

For example:

function foo()
	local run = true;
	local c = coroutine.wrap(function()
		while run do
			wait(1)
			print("foo");
		end
	end)
	
	c();
	
	wait(10);
	run = false;
end

If done right, you can send the function and change the value at a different time to stop it. You can make the variable global or adjust the scope to suit your needs.

This discussion is preserved as it was. New answers, comments, and votes are closed.