Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local meta={}
- local co=setmetatable({},meta)
- _G.co=co
- local costack=setmetatable({},{__index={
- push=function(tbl,val)
- table.insert(tbl,val)
- end,
- pop=function(tbl)
- return table.remove(tbl)
- end,
- current=function(tbl)
- return tbl[#tbl]
- end,
- }})
- co._re=function(thread,...)
- local status = coroutine.status(thread)
- if status=="running" then
- Msg"[CO] Running??? "print(thread)
- elseif status=="dead" then
- Msg"[CO] Dead "print(thread)
- elseif status=="suspended" then
- else
- error"invalid status?"
- end
- costack:push(thread)
- local ok,t,val = coroutine.resume(thread,...)
- costack:pop(thread)
- if not ok then
- ErrorNoHalt("Coroutine: "..tostring(t)..'\n')
- end
- if t=="sleep" then
- Msg"[CO] Sleep "print(val)
- timer.Simple(val,function()
- co._re(thread,"wait")
- end)
- elseif t=="cb" then
- Msg"[CO] wait for callback "print(val)
- return
- elseif t=="END" then
- Msg"[CO] END "print("OK")
- else
- Msg"[CO] Unhandled "print(t,val)
- end
- end
- function meta:__call(func)
- local thread = coroutine.create(function(...)
- func(...)
- return "END"
- end)
- co._re(thread)
- end
- function co.wait(delay)
- local ret = coroutine.yield("sleep",tonumber(delay) or 0)
- Msg"[CO] End wait "print(ret)
- end
- co.sleep=co.wait
- function co.newcb()
- local thread = costack:current()
- if not thread then error"wot" end
- Msg"[CO] Created cb for thread "print(thread)
- local CB CB = function(...)
- Msg("[CO] Callback called for thread ",thread," with params ")print(...)
- co._re(thread,"cbret",CB,...)
- end
- return CB
- end
- function co.waitcb(cbobj)
- local function wrap(cbret,CB,...)
- Msg"[CO] WaitCB " print(cbret=="cbret" and "OKRET" or ("WOT"..tostring(cbret)),(not cbobj or CB==cbobj) and "right cb" or "wtf cb?!?!?")
- Msg"[CO] WaitCB Params " print(...)
- return ...
- end
- return wrap(coroutine.yield("cb",cbobj))
- end
- -- TESTING --
- co(function()
- print"hello"
- co.wait(1)
- print"world"
- co.wait(1)
- print"!"
- local cb = co.newcb()
- timer.Simple(1,function()
- cb("callback","returning")
- end)
- local a,b,c,d=co.waitcb(cb)
- print("HTTP",b,c,d)
- co.wait(1)
- print"BYE"
- end)
Advertisement
Add Comment
Please, Sign In to add comment