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.
>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,returnor end (during the course of which"Hi"is printed) - control returns
"Bye"is printed