Coroutines and loops: C stack overflow

I’m replacing some code that used bindable events to coroutines and I’m coming across this error:

20:01:58.098 - false C stack overflow

This is the code that I’m using:

while true do
	local t = coroutine.running()
	print(t)
	coroutine.wrap(function()
		wait()
		warn(coroutine.resume(t))
	end)()
	coroutine.yield()
end

This is the code that uses BindableEvents to achieve similar functionality without any error:

local bindable = Instance.new("BindableEvent")

while true do
	coroutine.wrap(function()
		wait()
		bindable:Fire()
	end)()
	bindable.Event:Wait()
	print("looped")
end

Would anyone mind explaining me why the first block of code causes that error?

1 Like

I’m don’t fully understand why this is happening, but it doesn’t happen if you use spawn/delay instead:

Note: Spawn executes after current tick is complete, thus guaranteeing that we’ve already called yield before it is executed.

while true do
	local t = coroutine.running()
	print(t)
	spawn(function()
		warn(coroutine.resume(t))
	end)
	coroutine.yield()
end

Maybe this could give other people some hints as to why the original is having stack-overflow issues.

1 Like

top piece of code no longer errors :face_with_peeking_eye: :alien: :alien: :alien: :alien: :alien: :alien: :alien: