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

Coroutine returning 'Nil'? Why, and how do i fix it?

I don't know why it is returning 'nil', instead of bye?

local run = coroutine.wrap(function()
	while wait() do
		print("Hi")
		
		return "Bye"
	end
end)

local thing = run()
print(thing)

2 answers

✓ Accepted answer

You should avoid trying to have coroutines return data (or sending information back to them with coroutine.resume) if you also use a wait command - the wait command is telling Roblox to yield the coroutine for a period of time, and then automatically resume it later - but you're also trying to resume. So, if you do print(run()) at the end of your script, you'll actually get an error (presumably because what you're doing is conflicting with how Roblox handles wait).

If you delete the while wait() do and just have the function return "Bye", it works as you expect.

You can do

local run = coroutine.wrap(function()
	for i = 1, 3 do
		coroutine.yield(i)
	end
	coroutine.yield("done")
	return "return"
end)
for i = 1, 10 do
	print(i, run())
end

However, notice that the code errors when you attempt to call run() more times than it yields. You can instead use coroutine.resume and coroutine.create if you don't want it to error:

local co = coroutine.create(function()
	for i = 1, 3 do
		coroutine.yield(i)
	end
	coroutine.yield("done")
	return "return"
end)
for i = 1, 10 do
	print(i, coroutine.resume(co))
end

Further reading:

Replace your return under the end.

local run = coroutine.wrap(function()
    while wait() do
        print("Hi")

    end
return "Bye" -- Here
end)

local thing = run()
print(thing)

Hope this helps!

1 comment

0

If you run this, you will get Hi printed out infinitely and Bye does not display (it can't since while wait() do will loop forever)

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