Menu
Coddy logo textTech

Pausing with coroutine.yield()

Part of the Logic & Flow section of Coddy's Lua journey — lesson 50 of 54.

The real power of coroutines comes from the coroutine.yield() function. This is what allows a coroutine to pause itself in the middle of execution and hand control back to the code that resumed it.When a coroutine calls coroutine.yield(), it immediately stops running at that exact point. The next time you call coroutine.resume() on that coroutine, it will continue from right after the yield() call, as if nothing happened.Here's a simple example:
function countToThree()
    print("One")
    coroutine.yield()
    print("Two")
    coroutine.yield()
    print("Three")
end

local co = coroutine.create(countToThree)
coroutine.resume(co)  -- Prints "One", then pauses
coroutine.resume(co)  -- Prints "Two", then pauses
coroutine.resume(co)  -- Prints "Three", then finishes
Notice how each resume() call runs the coroutine until it hits a yield(). The coroutine remembers exactly where it stopped, including all its local variables and execution state.You can also pass values back when yielding. Any arguments you give to coroutine.yield() become the return values of coroutine.resume(). Note that coroutine.resume() always returns a boolean status as its first value (true if the coroutine ran without errors, or false if an error occurred), followed by any values passed to yield():
function giveNumbers()
    coroutine.yield(10)
    coroutine.yield(20)
end

local co = coroutine.create(giveNumbers)

-- status is true, value is 10
local status, value = coroutine.resume(co)
print(value)  -- Prints: 10

-- status is true, value is 20
status, value = coroutine.resume(co)
print(value)  -- Prints: 20
challenge icon

Challenge

Easy

Write a function createYieldingCoroutine that takes count and returns a string showing the output from a coroutine that yields values multiple times.

Create a coroutine that yields the string "Step X" for each step from 1 to count, for a total of count steps. Resume the coroutine count times to collect all yielded values. Return all the yielded values concatenated with newlines.

Logic:

  • Create a function that uses a loop to yield "Step 1", "Step 2", etc., up to count
  • After all yields, the function should complete (no final yield for "Done")
  • Wrap this function in a coroutine using coroutine.create()
  • Resume the coroutine count times, collecting each yielded value
  • Concatenate all yielded values with newline characters between them
  • Return the concatenated string

Parameters:

  • count (number): The number of steps to yield

Returns: A string containing all yielded values separated by newlines (string). Format: Step 1\nStep 2\nStep 3

Try it yourself

function createYieldingCoroutine(count)
    -- Write code here
end
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow