local function S(S,i)return S.time>i.time end local i={}i.prototype={}i.__index=i.prototype function i.new()local S={}S.currentTime=0 S._tasks={}setmetatable(S,i)return S end function i.prototype.schedule(Q,i,B)local P={co=B,time=Q.currentTime+i}table.insert(Q._tasks,P)table.sort(Q._tasks,S)end function i.prototype.step(i,S)i.currentTime=i.currentTime+S while true do local S=i._tasks[#i._tasks]if S==nil or S.time>i.currentTime then break end i._tasks[#i._tasks]=nil assert(coroutine.resume(S.co))end end return i
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