Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local taskManager = {}
- local tasks = {}
- local aliveTasks = {}
- local pidCount = 0
- local env_os = {}
- for i,v in pairs(os) do
- env_os[i] = v
- end
- function env_os.pullEventRaw(sFilter)
- while true do
- local data = {coroutine.yield()}
- if data[1] == sFilter or data[1] == "terminate" then
- return table.unpack(data)
- end
- end
- end
- function env_os.pullEvent( sFilter )
- local eventData = table.pack( env_os.pullEventRaw( sFilter ) )
- if eventData[1] == "terminate" then
- error( "Terminated", 0 )
- end
- return table.unpack( eventData, 1, eventData.n )
- end
- function taskManager.add(func,name)
- local env = setmetatable({},{__index = _ENV})
- env.os = env_os
- local pid = pidCount
- pidCount = pidCount + 1
- local task = {}
- task.pid = pid
- task.name = name or "unknown"
- func = setfenv(func,env)
- local function errorHandle()
- local err,info = pcall(func)
- if (not err) and task.onError then
- task.onError(pid,info)
- end
- end
- task.coroutine = coroutine.create(errorHandle)
- coroutine.resume(task.coroutine)
- tasks[pid] = task
- return pid
- end
- function taskManager.onError(pid,func)
- if tasks[pid] and tasks[pid].coroutine then
- tasks[pid].onError = func
- end
- end
- function taskManager.kill(pid)
- local task = tasks[pid]
- if task and task.coroutine then
- coroutine.resume(task.coroutine,"terminate")
- end
- tasks[pid] = {}
- end
- function taskManager.list()
- local taskTable = {}
- for i,task in pairs(tasks) do
- if task.coroutine then
- local taskinfo = {}
- taskinfo.pid = task.pid
- taskinfo.name = task.name
- taskTable[#taskTable+1] = taskinfo
- end
- end
- return taskTable
- end
- function taskManager.stop()
- for i,task in pairs(taskManager.list()) do
- if task.coroutine then
- taskManager.kill(task.pid)
- end
- end
- end
- function taskManager.run(...)
- local funcs = {...}
- for i,task in pairs(funcs) do
- taskManager.add(task)
- end
- while true do
- local event = {coroutine.yield()}
- aliveTasks = {}
- for i,task in pairs(tasks) do
- if task.coroutine and coroutine.status(task.coroutine) ~= "dead" then
- aliveTasks[#aliveTasks+1] = task
- end
- end
- if #aliveTasks == 0 then
- print("ENDED")
- return
- end
- for i,task in pairs(aliveTasks) do
- coroutine.resume(task.coroutine,unpack(event))
- end
- end
- end
- function displayTime()
- local m_term = term.native()
- local w,h = m_term.getSize()
- local newTerm = window.create(m_term,1,2,w,h-1)
- term.redirect(newTerm)
- while true do
- error("sjdfhaskj")
- local x,y = m_term.getCursorPos()
- m_term.setCursorPos(1, 1)
- m_term.clearLine()
- m_term.write(os.time())
- m_term.setCursorPos(x,y)
- end
- end
- _G.task = taskManager
- _G.task.run(function() dofile("rom/programs/lua.lua") end,displayTime)
Advertisement
Add Comment
Please, Sign In to add comment