by popular demand (ok, 1 person asked for it ), I have put together a few simple examples on how to work with luas coroutines. The first one is this:
local cr local function f() local n for n = 1, HEIGHT do coroutine.yield(n) end end function setup() cr = coroutine.create(f) end function draw() local ok, y = coroutine.resume(cr) if ok then background(40, 40, 50) fill(255, 255, 255, 255) ellipse(WIDTH / 2, y, 30) text(y, 100, HEIGHT - 20) else close() end end
This is a very basic setup of a main function and a coroutine, which illustrates a few things about coroutines. First, in order to use a coroutine, you first have to initialize it with coroutine.create. This does not yet start the coroutine, just creates a handle and some context for it. The coroutine is started and continued using coroutine.resume. The second thing this illustrates is that coroutine.yield works as a kind of return from the function, to which you can later come back again using coroutine.resume. Arguments to coroutine.yield are returned as the 2nd, 3rd and so on results from coroutine.resume. The first value returned is a status which tells you if you can call the coroutine again, if it is true, or not, i it is false. The third thing this example illustrates is that if you come back to a coroutine with resume, the function is in exactly the state you left it in.
A common use for this simple setup is creating iterators for for … in … do … end statements. This is so comon, tha a special function was introduced to ease that kind of stuff, namely coroutie.wrap. Example follows:
local function enum(a, b) return coroutine.wrap( function() local n for n = a, b do coroutine.yield(n) end end ) end function setup() end function draw() local i background(40, 40, 50) fill(255, 255, 255, 255) font("AmericanTypewriter") fontSize(32) for i in enum(12, 17) do text(i, WIDTH / 2, HEIGHT - 32 * i) end end
Coroutine.wrap calls coroutine.create on its argument and then returns a function that, when called, resumes the coroutine and returns all but the first (status) value returned by coroutine.resume.
For details about these functions, have a look at http://www.lua.org/manual/5.1/manual.html#5.2
More examples follow in the next 2 posts.