local function Q(Q,T)return Q.time>T.time end local T={}T.prototype={}T.__index=T.prototype function T.new()local Q={}Q.currentTime=0 Q._tasks={}setmetatable(Q,T)return Q end function T.prototype.schedule(N,T,t)local j={co=t;time=N.currentTime+T}table.insert(N._tasks,j)table.sort(N._tasks,Q)end function T.prototype.step(T,Q)T.currentTime=T.currentTime+Q while true do local Q=T._tasks[#T._tasks]if Q==nil or Q.time>T.currentTime then break end T._tasks[#T._tasks]=nil assert(coroutine.resume(Q.co))end end return T
local function taskCompare(a, b)
	return a.time > b.time
end

local TaskScheduler = {}
TaskScheduler.prototype = {}
TaskScheduler.__index = TaskScheduler.prototype

function TaskScheduler.new()
	local self = {}

	self.currentTime = 0
	self._tasks = {}

	setmetatable(self, TaskScheduler)

	return self
end

function TaskScheduler.prototype:schedule(delay, co)
	local task = {
		co = co,
		time = self.currentTime + delay,
	}

	table.insert(self._tasks, task)
	table.sort(self._tasks, taskCompare)
end

function TaskScheduler.prototype:step(deltaTime)
	self.currentTime = self.currentTime + deltaTime

	while true do
		local top = self._tasks[#self._tasks]

		if top == nil or top.time > self.currentTime then
			break
		end

		self._tasks[#self._tasks] = nil
		assert(coroutine.resume(top.co))
	end
end

return TaskScheduler