severedskullz wrote:Inny wrote:Coroutines are about describing sequential events using code, rather than using data structures.
I understood everything but this. Could you elaborate please?
I'll elaborate for the sake of the
wisdom of the ancients.
Love is event-driven. Those events are update, draw, keypressed, keyreleased, and so on (see:
callbacks). These are very useful, but require that you manipulate data from them, since you can't change the path of execution in another function (like in callback) without some variable. So, lets say you're showing a cutscene, your draw function may look like this:
Code: Select all
function draw_cutscene_where_important_stuff_happens()
if draw_kirby then kirby:draw() end
if draw_peach then peach:draw() end
if draw_hearts then hearts: draw() end
if draw_dedede then dedede:draw() end
end
The evented style of updating this cutscene probably needs a clock to decide when to and when not to draw things
Code: Select all
function update_cutscene_where_important_stuff_happens(dt)
clock = clock + dt
draw_kirby = (clock > 1000)
draw_peach = (clock < 4000)
draw_hearts = (clock > 1500) and (clock < 3000)
draw_dedede = (clock > 3000) and (clock < 4000)
end
Simple, but I've had to contrive the appearance and disappearance of the characters, and it's not clear what event happens when. In more complex scenes, it may be necessary to keep a table of events and run a clock that'll execute events in order, which can get pretty messy.
The alternate, using coroutines, would look like this
Code: Select all
cutscene_coroutine = coroutine.wrap(function()
draw_peach = true
wait(1000)
draw_kirby = true
wait(500)
draw_hearts = true
wait(1500)
draw_dedede = true
draw_hearts = false
wait(1000)
draw_peach = false
draw_dedede = false
end)
function update_cutscene_where_important_stuff_happens(dt)
cutscene_coroutine(dt)
end
The scene is clearer, since it describes in order and with code, the cutscene events that are supposed to happen.
The only missing code is the wait function, which is this simple (though it's not 100% precise).
Code: Select all
function wait(seconds)
while seconds > 0 do
seconds = seconds - coroutine.yield(true)
end
end
So coroutines gets you back to having a straight thread explaining the steps in what will happen, while allowing for other things to happen as well. It's sometimes described as Cooperative Multithreading.