type = type,
data = data,
defaultPrevented = false,
- timeStamp = os.clock(),
+ timeStamp = lua_async.clock(),
}, {__index = EventPrototype})
end
lua_async = {}
+if rawget(_G, "require") then
+ lua_async.socket = require("socket")
+end
+
+function lua_async.clock()
+ return lua_async.socket and lua_async.socket.gettime() or os.clock()
+end
+
function lua_async.step(dtime)
-- timers phase
lua_async.timeouts.step(dtime)
lua_async.limiting.pool[co] = {
limit = limit,
- next_yield = os.clock() + limit,
+ next_yield = lua_async.clock() + limit,
}
end
local co = assert(coroutine.running(), "check_limit called outside of an async function")
local limit = lua_async.limiting.pool[co]
- if limit and os.clock() >= limit.next_yield then
+ if limit and lua_async.clock() >= limit.next_yield then
lua_async.yield()
- limit.next_yield = os.clock() + limit.limit
+ limit.next_yield = lua_async.clock() + limit.limit
return true
end
end
function lua_async.run()
- local last_time = os.clock()
+ assert(lua_async.socket)
+ local last_time = lua_async.clock()
while true do
- local current_time = os.clock()
+ local current_time = lua_async.clock()
local dtime = current_time - last_time
last_time = current_time
lua_async.step(dtime)
+
+ local next = math.huge
+
+ for _, timeout in pairs(lua_async.timeouts.pool)
+ next = math.min(next, timeout.time_left)
+ end
+
+ for _, interval in pairs(lua_async.intervals.pool)
+ next = math.min(next, interval.time_left)
+ end
+
+ if next == math.huge then
+ return
+ end
+
+ lua_async.socket.sleep(next)
end
end