------------------- -- Session class -- ------------------- do Session = class() -- Static local sessions = {} function Session.getSessions() return sessions end function Session.updateSessions() for session,_ in pairs(sessions) do session:tick() end end function Session.addSession(session) sessions[session] = true end function Session.removeSession(session) sessions[session] = nil end -- Object function Session:init(console, func, callback, commandTable) self.thread = coroutine.create(func) self.console = console self.callback = callback self.commandTable = commandTable or {} self.started = false self.suspended = true self.nextTick = timer.getMilliSecCounter() end function Session:checkSession(state, ...) local co = self.thread if coroutine.status(co) == "dead" then if self.callback then self:callback(tuple(state, ...)) return end if not state then self.console:print("----- TRACEBACK -----") self.console:print("[" .. tostring(co) .. "] terminated unsuccesfully") self.console:print(tostring(...)) self.console:print("") else self.console:print("[" .. tostring(co) .. "] terminated succesfully") end -- remove session from sessions table sessions[self] = nil end end function Session:start(run) assert(not self.started, "Cannot start an already started session!") self.started = true self.suspended = false if not run then self:checkSession(coroutine.resume(self.thread, self)) end end function Session:suspend() self.suspended = true self:interrupt() end function Session:interrupt() coroutine.yield(self.thread) end function Session:triggerResume() self.suspended = false end function Session:sleep(n) self.nextTick = timer.getMilliSecCounter() + 1000 * n self:interrupt() end function Session:tick(forceTick) local time = timer.getMilliSecCounter() if (not self.suspended and self.nextTick <= time) or forceTick then self:checkSession(coroutine.resume(self.thread)) end end -- NOT thread safe! Bugged sessions *could* crash the script. Will be improved in future versions function Session:sendCommand(command, ...) local c = self.commandTable[command] if c then c(...) end end -- Links to console -- function Session:print(...) self.console:print(...) end function Session:write(str) self.console:write(str) end function Session:read() return self.console:read(self) end function Session:readLine(str) return self.console:readLine(self, str) end end