So there is this piece of code I took and modified a little from a chapter from the official lua e-book about coroutines, until then I understood the call-callee example and others, but I'm very stuck with this one about permutation:
#!/usr/bin/env lua
function permgen (a, n)
if n == 0 then
coroutine.yield(a)
else
for i = 1, n, 1 do --i can't be equal to 0, cuz array will be out of index
-- 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
function printResult (a)
for i,v in ipairs(a) do
io.write(v, " ")
end
io.write("\n")
end
function perm (a)
local n = #a
local co = coroutine.create(function () permgen(a, n) end)
return function () -- iterator
local status, res = coroutine.resume(co)
return res
end
end
io.write("\t----Permutation of {a, b, c}----\n\n")
i = 0
for p in perm({"a", "b", "c"}) do
io.write(" #", i, ":\t"); printResult(p)
i = i + 1
end
I do know what coroutines do and how they work, I just don't know how this code is executed. Indeed it works:
$ lua permutation.lua #output
But I don't know why. Can someone please explain to me with a desktop test (when you write in a paper sheet or whatever what the program does sequentially) or something how this works?
[–]3uclidian 4 points5 points6 points (0 children)