-----Original Message-----
From: Tony Papadimitriou
>In other words, I prefer this:
>function xxx(n)
> for i = 1, n do yield i*i end
>end
>
>to this:
>
>function xxx(n)
> return coroutine.wrap(function() for i = 1, n do coroutine.yield(i*i) end
>end)
>end
>Now, if the latter is more appealing to you, good for you.
>"In matters of taste, there can be no disputes."
>>Francisco Olarte.
>Tony P.
I have an oop lib of pure Lua, it use the objects as environment, and with a special attribute system(like the decorator in Python, but a little complex) can provide such “syntax sugar” like
require "PLoop"
_ENV = Module "Test" "v1.0" -- Create a module object as environment
import "System.Threading"
__Iterator__() -- Wrap the next function as iterator runs as coroutine
function iter(i, j, step)
for k = i, j, step or 1 do
coroutine.yield(k, k^2)
end
end
-- Use it like pairs, the coroutine is generated by a pool
-- and will be recycled automatically
for k, v in iter (1, 10, 1) do
print(k, v)
end
The trick is very simple, the environment is controlled by the module object, so it know when a new function is defined and registered attribute can be used on it, no doubt you can create your own version.