Skip to content

Instantly share code, notes, and snippets.

@TannerRogalsky
Created April 18, 2012 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TannerRogalsky/2413313 to your computer and use it in GitHub Desktop.
Save TannerRogalsky/2413313 to your computer and use it in GitHub Desktop.
Example of lua coroutines being used as iterators.
function permgen (a, n)
if n == 0 then
coroutine.yield(a)
else
for i=1,n do
-- put i-th element as the last one
a[n], a[i] = a[i], a[n]
-- generate all permutations of the other elements
permgen(a, n - 1)
-- restore i-th element
a[n], a[i] = a[i], a[n]
end
end
end
-- just to print the table properly
function printResult(a)
for i,v in ipairs(a) do
io.write(v, " ")
end
io.write("\n")
end
function perm (a)
local co = coroutine.create(function () permgen(a, #a) end)
local iterator = function ()
local code, res = coroutine.resume(co)
return res
end
return iterator
end
for p in perm({"a", "b", "c"}) do
printResult(p)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment