running() returns a reference to the current coroutine and a boolean that indicates if the execution is currently in the main coroutine.
running()function in Lua which returns the coroutine running the function. If the function is not running inside a coroutine, it returns
- There are several coroutine functions used to manage these objects, including
create(), which creates new coroutines, and
yield(), which allows a running coroutine to suspend its execution so that it can be resumed later.
This example uses
coroutine.running() to print coroutine IDs, both from the main thread and within a coroutine.
function printCurrentCoroutineID()local currentCoroutine = coroutine.running()if currentCoroutine thenprint("Current coroutine ID:", currentCoroutine)elseprint("Not running inside a coroutine")endendprint("Printing from the main thread")printCurrentCoroutineID()-- Create a coroutine and print from itlocal myCoroutine = coroutine.create(function()print("Printing from the coroutine")printCurrentCoroutineID()end)coroutine.resume(myCoroutine)
The output will be similar to:
Printing from the main threadCurrent coroutine ID: thread: 0x55eed07642a8Printing from the coroutineCurrent coroutine ID: thread: 0x55eed076bbf8