← Back to Lua Course | Chapter 7: Coroutines | Lesson 4 of 7

coroutine.wrap

wrap gives you a plain function that resumes the coroutine each time it is called.

In this page:

  1. coroutine.wrap

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

lua
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
Common Mistakes
  1. Expecting wrap to return a coroutine object
  2. Expecting errors to be returned as false and a message
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.