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