Search code examples
lua

Can a function know whether it is running inside a coroutine?


Is there a way for a function to know if it is being run within a coroutine?

For example I have a send_message() function that tries three times to send a message. Between each try it needs to wait one second. If this function is being called from within a coroutine, I'd like the send_message() function to do a coroutine.yield() as part of its wait-1-second loop. But if it's not within a coroutine, then it should do a POSIX usleep() instead.

Is there a way to do this?


Solution

  • I should have looked better in the Lua reference manual: coroutine.running() returns nil if called by the main thread, which is perfect for this case.

    The original reason for asking was that I was mixing up coroutine.running() with coroutine.status().

    See: http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running and: http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status

    Be aware that behavior changed in Lua 5.2:

    Returns the running coroutine plus a boolean, true when the running coroutine is the main one.

    See https://www.lua.org/manual/5.2/manual.html#pdf-coroutine.status