yield()
Published Oct 18, 2023
Contribute to Docs
The yield()
function suspends the current coroutine and returns its arguments to the caller. When subsequently resumed, yield()
will return any arguments that were passed to resume()
, and pick up where it left off.
Syntax
coroutine.yield(...)
- The
yield()
function is used to temporarily pause the execution of a coroutine and return control to the coroutine that resumed it. - When
coroutine.yield()
is called, any arguments passed to it are returned by the correspondingcoroutine.resume()
call that started the coroutine. - The arguments passed to
coroutine.resume()
are available as return values of theyield()
function call that suspended the coroutine before.
Example
The example below demonstrates how the yield()
function allows the coroutine to pause its execution and restart from the same point.
function myCoroutine()print("Hello, Codecademy!")coroutine.yield()print("How are you?")endco = coroutine.create(myCoroutine)coroutine.resume(co)coroutine.resume(co)
This will result in the following output:
Hello, Codecademy!How are you?
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.