Chaining timers, events, etc. May have just found a cool way to do this!

So I have been trying to add some events to my game.  For example a boss dies and the screen flashes multiple times leading up to a final boss.  I would always end up with a pyramid of death…  something like this:

function events.spawnEmmabot(fn) Runtime:dispatchEvent({name="flashScreen", fn=function() m.addTimer(400, function() Runtime:dispatchEvent({name="flashScreen", fn=function() m.addTimer(200, function() Runtime:dispatchEvent({name="flashScreen", fn=function() m.addTimer(4000, function() Runtime:dispatchEvent({name="flashScreen", fn=function() fn() end}) end,1) end}) end,1) end}) end,1) end}) end

Seemed to me like these things should be chained… so i set out finding a way to accomplish that.  So I actually got the above code down to this:

function events.spawnEmmabot(fn) local chain = h.chain.new() chain:run({ {dispatch="flashScreen"}, {timer=400}, {dispatch="flashScreen"}, {timer=200}, {dispatch="flashScreen"}, {timer=4000}, {dispatch="flashScreen"}, {fn=fn} }) end

Now I can chain stuff together!  so far I can chain dispatch events, timers and random code blocks.  I could also extend this to chain transitions!.  Havent done that yet though

 This is the code I threw together in order to chain different events.

local helper = {} helper.chain = {} function helper.chain.new() local function formatEvent(self, event, counter) local func = function() end if event then if event.dispatch then func = function() Runtime:dispatchEvent({name=event.dispatch, onComplete=self:formatEvent(self.sequence[counter+1], counter+1)}) end elseif event.timer then func = function() m.addTimer(event.timer, self:formatEvent(self.sequence[counter+1], counter+1), 1) end elseif event.fn then func = event.fn() end end return func end local function run(self, events) self.sequence = events self:formatEvent(self.sequence[1], 1)() end local chain = {} chain.sequence = {} chain.formatEvent = formatEvent chain.run = run return chain end

Note.  the m.timer is just my way of keeping track of timers for pausing purposes.  I’m sure this code could be rewritten in a better way but I thought this concept might help someone?  Forgive me if its a waste of time.