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

How to stop a coroutine? {Unanswered}

I looked for a specific coroutine function that would stop a coroutine, but I couldn't find one. Is there a legitimate way to pause or delete a coroutine?

3 answers

I don't believe there is a function to stop a co-routine. The only way to stop one is to disable the script (this may not work, I haven't tried it), let it finish, or make an error.

Example:

local forceQuit = 0

coroutine.wrap(function()
	while forceQuit==0 do
		wait()
		print('Coroutine running')
	end
	print('Coroutine finished.')
end)()
wait(5)
forceQuit=1

This should stop it in 5 seconds. You can also make it have an error.

local forceQuit = 0

coroutine.wrap(function()
	while wait() do
		print('Coroutine running')
		if forceQuit==1 then error('Coroutine errored') end
	end
	print('Coroutine finished.')
end)()
wait(5)
forceQuit=1

-- Edit -- I've just read your other question, if there is a way to pause one. There is, but it's not a built-in roblox function.

This will pause it 5 times for 3 seconds (or 4 times, I get confused, but you get how it works.)

local pause=false

coroutine.wrap(function()
	while wait() do
		print('coroutine running')
		if pause==true then
			while pause==true do wait() end	
		end
	end
end)()

for i = 1, 5 do
	wait(5)
	pause=true
	wait(3)
	pause=false
end

There is a way to 'pause', or suspend a coroutine, and that is done by the 'yield()' method.

EXAMPLE FROM WIKI

new_thread=coroutine.wrap(function(param)
	print(param)
	local resumedWith = coroutine.yield()
	print("Resumed with: " .. resumedWith)
end) 
new_thread("Hola mis amigos!")
new_thread("This was retrieved with yield()")

From what I understand, the new_thread coroutine will print the 'param' argument and then suspend it. It is then called by the "Hola mis amigos!" string. If it is called on again, it will print "Resumed with: This was retrieved with yield()".

For more information on coroutines, visit here and its links.

Sorry for the short answer and the lack of dense explanation. I tried many examples, but they do not seem to work as expected after I've tested them. Originally, I thought I had an answer until a plethora of errors had hit me and left me uncertain.

I'm apparently very inexperienced with coroutines, but once I know more about them, I'll check back here.

An effective way to stop a coroutine (and the only way I know) is to stop the thread it is looping through, by either an error or a change.

An example of this is here:

coroutine.create(coroutine.resume(function() --would rather use spawn(function() but oh
	print('val!')
	priint('val!)
end)

I also prefer using spawn(function()as it is faster and neater.

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