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