Lua create()

deenovita's avatar
Published Oct 19, 2023
Contribute to Docs

create() is used to create a new coroutine with a function as an argument that will run within the new coroutine. This function returns a type thread value. When a new coroutine is created, the status is ‘suspended’. The .resume() method is used to run or initiate the coroutine. When the execution has completed the coroutine is designated ‘dead’.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours

Syntax

co = coroutine.create(newFunc)

Where newFunc is used as an argument to run within the new coroutine.

Example

The following example shows the implementation of the function and its output.

-- Create a new coroutine named co_great
co_great = coroutine.create(function (name)
print("Hi, " .. name)
end)
-- Check a new coroutine status
print(coroutine.status(co_great))
-- Run a new coroutine
print(coroutine.resume(co_great, "Alice"))
-- Check again after it was run
print(coroutine.status(co_great))

The output will look like this below:

suspended
Hi, Alice
true
dead

All contributors

Contribute to Docs

Learn Lua on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours