Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(LUA) Why is this coroutine wrap doesn't seem to work?

My code here:

coroutine.wrap(function()
    local x = os.clock() + 3
    repeat until os.clock() >= x
    print("Hi")
end)()

print("Bye")

Usually, the expected output should be "Bye" and then wait 3 seconds to print "Hi".
However, the coroutine yielded first and printed Hi before Bye.

Did I do something wrong in my code? I am new to coroutines.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Coroutines are not threads. They do not run simultaneously; only one coroutine inside a thread can run at a time. Once you resume a coroutine (which is what a call to a wrapped coroutine basically does), it runs until it yields control back to the original place which is waiting for a value to be yielded. Since you have no yield in the coroutine, it will run to completion when invoked. So your code

  • declares an anonymous function
  • makes a coroutine wrapper
  • resumes the coroutine by invoking the wrapper
  • the function runs until yield, return or end (during the course of which "Hi" is printed)
  • control returns
  • "Bye" is printed
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading