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)
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)
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!
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
If you run this, you will get
Hiprinted out infinitely andByedoes not display (it can't sincewhile wait() dowill loop forever)