Menu
Coddy logo textTech

coroutine create & resume

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

Now that you understand what coroutines are, let's learn how to actually create and run them in Lua.

To create a coroutine, you use the coroutine.create() function. This function takes a regular function as its argument and wraps it into a coroutine object. Here's the basic syntax:

function myTask()
    print("Hello from coroutine!")
end

local co = coroutine.create(myTask)

At this point, the coroutine exists but hasn't started running yet. The function myTask hasn't been called. To actually start or continue a coroutine's execution, you use coroutine.resume():

coroutine.resume(co)

When you call resume() on a coroutine for the first time, it starts executing from the beginning of its function. If the coroutine runs all the way through without pausing, it completes and cannot be resumed again.

Here's a complete example:

function greet()
    print("Starting...")
    print("Finishing!")
end

local co = coroutine.create(greet)
coroutine.resume(co)  -- Prints both messages

The coroutine runs from start to finish in one go. In the next lesson, you'll learn how to make coroutines pause in the middle of execution.

challenge icon

Challenge

Easy

Write a function runSimpleCoroutine that takes a message and returns the output from a coroutine that prints that message.

Create a coroutine using coroutine.create() that wraps a function which prints the provided message. Then use coroutine.resume() to execute the coroutine. The function should return the message that was printed.

Logic:

  • Define a function that prints the message parameter
  • Create a coroutine from that function using coroutine.create()
  • Resume the coroutine using coroutine.resume()
  • Return the message that was printed

Parameters:

  • message (string): The message to be printed by the coroutine

Returns: The message that was printed by the coroutine (string)

Cheat sheet

To create a coroutine, use coroutine.create() with a function as its argument:

function myTask()
    print("Hello from coroutine!")
end

local co = coroutine.create(myTask)

To start or continue a coroutine's execution, use coroutine.resume():

coroutine.resume(co)

Complete example:

function greet()
    print("Starting...")
    print("Finishing!")
end

local co = coroutine.create(greet)
coroutine.resume(co)  -- Prints both messages

When resume() is called for the first time, the coroutine starts executing from the beginning. If it runs to completion without pausing, it cannot be resumed again.

Try it yourself

function runSimpleCoroutine(message)
    -- 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