coroutine.wrap
wrap gives you a plain function that resumes the coroutine each time it is called.
In this page:
coroutine.wrap
coroutine.wrap(f) returns a function that resumes the coroutine on every call and returns the yielded values without the leading true. If an error happens inside, it is propagated to the caller instead of being returned as a status. This makes wrap convenient for iterators.
Note:
Use create when you need the status, and wrap when you just want a function.
Example: coroutine.wrap
local gen = coroutine.wrap(function()
for i = 1, 3 do coroutine.yield(i) end
end)
print(gen(), gen(), gen())
print(type(gen))
gen()
print(pcall(gen))
-- Output:
-- 1 2 3
-- function
-- false cannot resume dead coroutine
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting wrap to return a coroutine object
- Expecting errors to be returned as false and a message
- Calling a wrapped coroutine after it has finished
Chapter Summary
- wrap returns a function
- No status boolean is returned
- Errors propagate to the caller
- Calling a finished wrap raises an error
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: