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

Viewed 164

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.

1 Answers

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
Related