Coroutine.yield not stopping a while loop

For some reason, coroutine.yield does not a running loop in a coroutine.

Here’s a basic proxy of my code:

local routine = coroutine.create(function()
	while true do
		print("Running..")
		wait(1)
	end
end)

coroutine.resume(routine)
wait(3) -- should print 3 times
coroutine.yield(routine)

After coroutine.yield has been called, it continues to print.

This is confusing behavior - anyone know any solutions?

Do I need to make my own ‘enabler’ bool variable? I don’t really want to, for performance reasons.

1 Like

Not an expert on this subject, but I’m pretty sure it’s something like wait() internally calls yield and also adds the thread to the internal Roblox thread scheduler while regular yield does not. This would cause the thread to be automatically resumed by the thread scheduler.

1 Like

So I would need to somehow not use wait?

In that case I’m not sure if it’s possible (assuming signal:Wait() also counts as wait).

My current solution is just putting the while loop directly into the code that would resume the coroutine.

Pretty sure you need to call coroutine.yield from inside your coroutined function:

local routine = coroutine.create(function()
	while true do
		print("Running..")
		coroutine.yield()
	end
end)

for i = 1,3 do
   coroutine.resume(routine)
end
3 Likes

In that case my current solution seems to be the best option:

enabled = true
while enabled do
    -- code
end

-- somewhere else
enabled = false

After all, there’s no point complicating it with more operations.

It’d be pretty useful if coroutine.yield could be called with a time value :wink:

Thanks for the help