Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lua

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?

like image 716
proFromDover Avatar asked Feb 26 '23 09:02

proFromDover


1 Answers

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

like image 143
proFromDover Avatar answered May 20 '23 10:05

proFromDover