What do you want to achieve?
I would like some help understanding how returning works with coroutine.wrap()
What is the issue?
I have a function that runs a loop and after the loop simply returns something. In this case it’s returning a string. I thought that storing a coroutine into a variable would turn it into what was returned. However, I am getting nil after printing the variable.
Please see the function below:
function getNumbers()
for i = 1, 5 do
print(i)
wait(1)
end
return "Loop ended"
end
local co = coroutine.wrap(getNumbers)()
wait(5)
print(co)
You probs shouldnt use coroutine.wrap() to spawn a function, however, you can make the function itself inside a coroutine.wrap() and you will have a working result.
It’s better to check if the coroutine is done running with co.status, or it will be nil if it’s not done running. this is the script
function getNumbers()
for i = 1, 5 do
print(i)
wait(1)
end
return "Loop ended"
end
local co = coroutine.wrap(getNumbers)()
if co.status == 'suspended' then
print(co)
end
I read already previously read the docs and the official lua online handbook. The thing about using wrap, you cannot obtain it’s status. This is because .status looks for a thread however wrap returns a function instead of a thread. So unfortunately the code you provided wouldn’t work.
Your co argument is receiving whatever is returned when the wrapped coroutine reaches an exit point in its code. In your case, that is not your defined return exit point, but rather when the code yields at the wait() call. This exit point does not return anything to the code that resumed the coroutine, and so your co variable is nil.
If you need to get information from your loop without it blocking the main thread, consider having it fire an event when it reaches the end of the loop instead of returning a value, then listing for that event from your main thread.
Yeah after some testing around, I made the code yield the result at the end of the loop and the corresponding call will have the result as resume-yield pairs do. Thank you.