Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function safePairs(_t)
- local tKeys={}
- for k,_ in pairs(_t) do
- table.insert(tKeys,k)
- end
- local nAt=0
- return function()
- nAt=nAt+1
- return tKeys[nAt]
- end
- end
- local function create(...)
- local tThreads={}
- for k,_thread in pairs({...}) do
- if type(_thread)~="function" then
- error("Invalid param #"..k.." function expected, got "..type(_thread),2)
- end
- tThreads[k]={thread=coroutine.create(_thread),func=_thread,living=true,env=getfenv(_thread)}
- end
- return tThreads
- end
- local function runUntilLimit(tRoutines,nLimit)
- local running
- local tUtils_mt={}
- local tUtils=setmetatable({},tUtils_mt)
- tUtils.addRoutines=function(...)
- for _,tThread in ipairs(create(...)) do
- table.insert(tRoutines,tThread)
- end
- end
- tUtils.getRunning=function()
- return running
- end
- tUtils.getRoutines=function(sName,...)
- if sName==nil then
- return nil
- end
- return tRoutines[sName or running],tUtils.getRoutines(...)
- end
- tUtils.killRoutines=function(sName,...)
- if sName==nil then
- return nil
- elseif tRoutines[sName] and tRoutines[sName].living then
- tRoutines[sName].living=false
- tRoutines[sName].error="killed"
- return true,tUtils.killRoutines(...)
- else
- return false,tUtils.killRoutines(...)
- end
- end
- tUtils.runningRoutines=function()
- local count=0
- for i=1,#tRoutines do
- if tRoutines[i].living then
- count=count+1
- end
- end
- return count
- end
- local tEvts={}
- while true do
- local nRunning=0
- for k,v in pairs(tRoutines) do
- if type(v.thread)=="thread" and type(v.func)=="function" and v.living then
- running=k
- tUtils_mt.__index=v.env
- setfenv(v.func,tUtils)
- local ok,err=coroutine.resume(v.thread,unpack(tEvts))
- setfenv(v.func,v.env)
- running=nil
- if not ok or coroutine.status(v.thread)=="dead" then
- v.living=false
- v.error=err
- elseif living then
- nRunning=nRunning+1
- end
- if tUtils.runningRoutines()<=nLimit then
- return tRoutines
- end
- end
- end
- tEvts={os.pullEventRaw()}
- end
- end
- function waitForAny(...)
- local routines=create(...)
- return runUntilLimit(routines,#routines-1)
- end
- function waitForAll(...)
- local routines=create(...)
- runUntilLimit(routines,0)
- end
Advertisement
Add Comment
Please, Sign In to add comment