Coroutine not stopping after cancel

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    Im attempting to use coroutines to control a loop from the outside however it’s not working as intended.

Here’s the code

local  LoopCoro1 = coroutine.create(function()
		--repeat
		while true do
			for i = 1, 4 do
				Phase1()

				wait(LightingWaitPeriod)

				Phase1()

				wait(LightingWaitPeriod)

				Phase1(true)

				wait(LightingWaitPeriod)

				Phase1(true)

				wait(LightingWaitPeriod)
			end


			LightingWaitPeriod = .05

			for i = 1, 6 do
				Phase3()

				wait(LightingWaitPeriod)

				Phase3(true)

				wait(LightingWaitPeriod)
			end
		end
		--until script:GetAttribute("ELS_ON") == false
	end)
	
	coroutine.resume(LoopCoro1)
	
	script:GetAttributeChangedSignal("ELS_ON"):Connect(function()
		local value = script:GetAttribute("ELS_ON")
		if value == false then
			warn("Yield")
			coroutine.yield(LoopCoro1)
			coroutine.close(LoopCoro1)
		end
	end)

When I call coroutine close, the loop does not stop. Maybe I’m not understanding, but I’ve seen multiple times it should hault.

1 Like

Your code isn’t formatted correctly, but I don’t think you should really be using a coroutine. You should detect if the value changed then start the loop in the same thread and repeat it until a local variable turns to false. The local variable will turn to false when the value changes to false and it will stop the loop and turn off the lights.

1 Like

The problem is in this line

This line makes the current thread yield just before closing the LoopCoro1 thread (coroutine.close(LoopCoro1)).
Just comment out that line.

2 Likes

I decided to learn how to use coroutines since they’re the only thing that can stop a loop process dead in it’s tracks. I made some changes to how I arranged them though so I think it’s a bit cleaner now

This was the issue! After I commented it out things work fine. I do get an error that says “cannot resume dead coroutine ” but I’ll find a fix later on. For now everything seems to be working perfectly as intended. :pray: thank you

Unfortunately, this is buried into the Roblox engine, and you cannot remove it. This is one of the reasons why I don’t recommend a coroutine.

local runLoop = false
function startLoop()
runLoop = true
while runLoop do
--stuff
end
end
function stopLoop()
runLoop = false
end

The above code might be a better way to rearrange your code, as I’ve stated in the previous post.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.