Help with coroutine.wrap()

  1. What do you want to achieve?
    I would like some help understanding how returning works with coroutine.wrap()

  2. 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)

The output comes out as:
1 through 5
then
nil

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

For better understanding read the docs

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.

3 Likes

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.

1 Like

Depending on what you’re trying to do, coroutine.yield may be what you’re looking for.
Similar question and answer here: How to get a returned value from a wrapped yielding function

1 Like

Yup, just as I posted, I ended up using it at the end of the loop and got the result I wanted. Thank you for your reply :slight_smile:.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.