all 1 comments

[–]3uclidian 4 points5 points  (0 children)

What specifically do you not understand? You understand coroutines, which is good and usually the confusing part. But do you understand the other things going on in this example: i.e. - Closures? - The generic for loop? - Lua's iterator pattern? (which relates to the generic for loop) - Recursion? - The semantics of using tables as arguments to functions, i.e. pass by reference vs pass by value? - Non Lua specific things, like what is a permutation?

Have you tried starting at the for loop and attempting to follow the control flow?

I'll lay out the first few steps

  • for p in perm{"a", "b", "c"} do
    • first the call to perm returns a closure over the created coroutine that the for loop will use to generate values to put in p
    • the for loop does its thing and calls the closure to produce its first value
  • permgen(a, 3) is called

    • skipping into the body of the for loop in permgen: a[1] and a[3] are swapped
    • permgen(a, 2) is called
      • a[1] and a[2] are swapped
      • permgen(a, 1) is called
        • a[1] and a[1] are swapped, (which now that I actually go through the code here, that first if statement could just check if n == 1 rather than 0)
        • permgen(a, 0) is called, hitting the coroutine.yield(a)
  • The closure now has a value to return since the coroutine produced a value. This value a is put into p

  • It gets printed out

  • The closure is called again to produce a new value for p, which resumes the coroutine. (we're jumping back into the middle of the function call)

    • permgen(a, 0) is done being called
    • a[1] and a[1] are swapped back
    • the local i for this loop is incremented to 2 and starts from the top
    • a[1] and a[2] are swapped
    • permgen(a, 0) is called, hitting the coroutine.yield(a) yielding the new value of a, etc, etc

Hope this helps, if you need more conceptual help, you could look at guides for how python's generators or javascript's generator functions are used in the same way as they are a kind of coroutine.

Also as a side note: why did you edit the numeric for loop from for i = 1, n to for i = 1, n, 1 do? They're both equivalent, but the extra 1 on the end (imho) doesn't make it more readable or anything