Waiting for a coroutine

I’ve made a coroutine using the coroutine.create() function, and I can resume it and use it fine. However, I want to be able to wait for a coroutine to finish. Is it possible to wait for a coroutine to complete the function it holds, or are they only for multi-threading?

What you are asking for is indeed possible.
Here’s an example:

-- // Create a coroutine
local TheCoroutine = coroutine.create(function()
	-- // Some code here
	coroutine.yield("Done");
end);

-- // Resume the coroutine
coroutine.resume(TheCoroutine);

-- // Wait for the coroutine to complete
local Status, Result = coroutine.resume(TheCoroutine);
if (Status and Result == "Done") then
	print("Coroutine completed successfully");
end;

Coroutines are not only for multi-threading, they can also be used to implement cooperative multitasking or to perform asynchronous operations.
With coroutines, you can write code that looks synchronous but is actually asynchronous under the hood.

1 Like

I’ve tried using this implementation, but the result keep returning “nil”. The TypeWrite function has coroutine.yield(“Done”) at the end as well.

writingFunction = coroutine.create(TypeWrite)
		
		coroutine.resume(writingFunction, text)
		local success, result = coroutine.resume(writingFunction)

		repeat
			task.wait()
			print(success)
			print(result)
		until success == true and result == "Done"

You are passing text as an argument to the coroutine function TypeWrite.
When you call coroutine.resume(writingFunction) again, you’re not passing any argument, so TypeWrite is getting called with no argument, which might be causing the issue.

Try this:

writingFunction = coroutine.create(TypeWrite)
coroutine.resume(writingFunction, text)

repeat
    task.wait()
    local success, result = coroutine.resume(writingFunction)
    print(success)
    print(result)
until success == false or result == "Done"
1 Like

I tried this solution, and it says that the coroutine cannot be resumed, as it is dead, which confuses me as the coroutine.yield(“Done”) isn’t doing anything at the bottom of the TypeWrite function.

The coroutine has probably completed before the repeat loop starts, which would cause it to be dead by the time you try to resume it.

1 Like

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