Skip to content

Instantly share code, notes, and snippets.

@CoderPuppy
Created July 25, 2016 03:58
Show Gist options
  • Save CoderPuppy/1a21ebdd19f0c6cf89da5173a6810488 to your computer and use it in GitHub Desktop.
Save CoderPuppy/1a21ebdd19f0c6cf89da5173a6810488 to your computer and use it in GitHub Desktop.
Lazy streams with coroutines
local function pull(c)
if coroutine.status(c) == 'dead' then
return false
else
local ok, res = coroutine.resume(c)
if coroutine.status(c) == 'dead' then
return false
elseif ok then
return true, res
else
error(res)
end
end
end
local function printS(c)
while true do
local ok, v = pull(c)
if ok then
print(v)
else
break
end
end
end
local function fromList(l)
return coroutine.create(function()
for _, v in ipairs(l) do
coroutine.yield(v)
end
end)
end
local function init(c)
return coroutine.create(function()
local ok, v1 = pull(c)
while true do
local ok, v2 = pull(c)
if ok then
coroutine.yield(v1)
v1 = v2
else
break
end
end
end)
end
printS(init(fromList({1, 2, 3, 4, 5})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment