Skip to content

Instantly share code, notes, and snippets.

@zserge
Created July 22, 2014 12:28
Show Gist options
  • Save zserge/b027eb29293e2a499700 to your computer and use it in GitHub Desktop.
Save zserge/b027eb29293e2a499700 to your computer and use it in GitHub Desktop.
--
-- Let you write code like
-- chain(func1):next(func2):next(func3):go()
--
function chain(cb)
local queue = {}
local n, go;
go = function()
local cb = table.remove(queue, 1)
if cb then cb(go) end
end
n = {
next = function(a1, a2)
local cb = a2 or a1
table.insert(queue, cb)
return {
next = n.next,
go = go
}
end,
go = go
}
return n.next(cb)
end
--
-- Example
--
local c = chain(function(done)
print('X')
done()
end):next(function(done)
print('Y')
done()
end):next(function(done)
print('Z')
done()
end):go()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment