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