Skip to content

Instantly share code, notes, and snippets.

@meepen
Created January 29, 2017 02:51
Show Gist options
  • Save meepen/6f98680f1523247619ceecb38d54c8d9 to your computer and use it in GitHub Desktop.
Save meepen/6f98680f1523247619ceecb38d54c8d9 to your computer and use it in GitHub Desktop.
async.lua
local LOCALVERSION = 0
local async_mt = {}
local async = setmetatable({}, async_mt)
async.VERSION = LOCALVERSION
async.await = function(fn)
return coroutine.yield(fn)
end
local function _pack(...)
return table.pack and table.pack(...) or {n = select("#", ...), ...}
end
local function _unpack(dat, starts, ends)
return (table.unpack or unpack)(dat, starts or 1, ends or dat.n)
end
local function _call(a, ...) return a(...) end
async_mt.__call = function(async, fn, retvals)
local co = coroutine.create(fn)
local function iterator(...)
if (coroutine.status(co) == "suspended") then
assert(type((...)) == "function", "need function in async.await")
(...)(function(...)
local rets = _pack(coroutine.resume(co, ...))
assert(rets[1], "failed to run code")
iterator(_unpack(rets, 2))
end)
else
retvals(...)
end
end
local rets = _pack(coroutine.resume(co))
assert(rets[1], "failed to run code")
iterator(_unpack(rets, 2))
end
--[[
function fetch_db_data()
return async.await(function(callback)
-- async library code
-- async_timer_callback(0.1, callback, "<error>")
-- timer.Simple(0.1, function() callback "<error>" end)
end)
end
async(function()
return fetch_db_data(), fetch_db_data()
end, function(...)
print(...)
end)
]]
return async
Copy link

ghost commented Jan 29, 2017

hi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment