>>29
local makes a variable that is local to the function. If you didn't have the local, the variable would be global. I think variables are local by default in python? That lua code is only cryptic because it is doing weird stuff. It also doesn't help that you have to guess which arguments to the function are actually functions, and what their usages are.
function(operator_function)
operator_function(blah)
end
is the same as:
function(f)
f(blah)
end
It's a function that takes as an argument, another function, which is then applied to something some number of times. There are times where this can be useful, and it is one way you can get some polymorphism in C. If you've never seen this style before, or if you've never seen continuations, coroutines before, you should note that this example isn't very useful, and there are times where they can be less complex and more practical.
http://lua-users.org/wiki/CoroutinesTutorial
http://www.lua.org/pil/9.1.html
In my experiences, I've only used coroutines to create iterators. Say you have some algorithm that calculates some sequence of numbers, and you would like to iterate through these numbers. One simple solution could be to have the function that calculates the sequence fill the numbers into an array, and then you can iterate through the array. One problem with this is that you need to predict in advance how many numbers from the sequence you need to iterate through. Another is the amount of memory needed for the large array. In some situations, it would be nice to generate the sequence of numbers as you need them. That way, you can iterate through the sequence of numbers indefinitely. So what you can do is create two threads, running at the same time. Thread A will generate the sequence of numbers, passing to thread B, which will then do something with the numbers. Thread A only runs when B asks A for a number. A calculates the number, hands it to B, and then passes execution over to B. When B needs another number, it will pass execution back to A. A will resume from the same state that it was in before it stopped before, and it will then generate the next number.
So:
A = coroutine.wrap(function()
coroutine.yield(1)
coroutine.yield(2)
coroutine.yield(3)
coroutine.yield(4)
coroutine.yield(5)
end)
function B()
print(A()) -- prints 1
print(A()) -- prints 2
print(A()) -- prints 3
print(A()) -- prints 4
print(A()) -- prints 5
print(A()) -- prints nil
end
This might not look very useful, but note that you can put coroutine.yield inside of a loop, or in a recursive call. The function call stack and all that is saved and execution will continue later.
You can do other things with coroutines, but so far, I haven't gone there yet.