Syntax
local nextValue = coroutine.wrap(function() coroutine.yield(value) end)Examples
Lua coroutine iterators with wrap
Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.
local nextSquare = coroutine.wrap(function()
for n = 1, 3 do coroutine.yield(n * n) end
end)
for square in nextSquare do print(square) end- Output: 1, 4, 9. A final resume returns no value and ends the generic-for loop.
Best practices
- Do not resume the wrapped function after completion. nil terminates generic-for iteration, so it cannot be an ordinary yielded item in this pattern.
Runtime & versions
Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Lua reference manuals