close()
Published Oct 7, 2023
Contribute to Docs
The close()
function in Lua’s coroutine module is employed to gracefully terminate a coroutine and release its associated resources.
It yields a boolean value, true
, if the coroutine has been successfully closed, otherwise it returns false
.
Syntax
coroutine.close(coroutine_thread)
- The
close()
function is used to explicitly release resources associated with a coroutine, making it safe to close coroutines that have finished their execution. - Attempting to close a running coroutine or a coroutine that has already been closed will result in an error.
- Always check the return values of
coroutine.close()
to handle potential errors appropriately.
Example 1
This example uses the close()
function to terminate a running coroutine.
local function myCoroutine()print("Coroutine is running")coroutine.yield()print("Coroutine has resumed")endlocal co = coroutine.create(myCoroutine)coroutine.resume(co) -- Start the coroutinelocal success, error_message = coroutine.close(co)print("Closing coroutine:", success, error_message)
The output is:
Coroutine is runningClosing coroutine: true nil
Example 2
This example creates a coroutine using coroutine.create()
, starts it with coroutine.resume()
, and then closes it with coroutine.close()
.
local function manageCoroutine()local co = coroutine.create(function ()print("Coroutine is running")coroutine.yield()print("Coroutine has resumed")end)coroutine.resume(co) -- Start the coroutinelocal success, error_message = coroutine.close(co)if success thenprint("Coroutine closed successfully")elseprint("Error while closing coroutine:", error_message)endendmanageCoroutine()
This will output:
Coroutine is runningCoroutine closed successfully
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.
Learn Lua on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Lua
Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.Beginner Friendly4 hours