]> git.lizzy.rs Git - lua_async.git/blobdiff - util.lua
Merge branch 'master' of https://github.com/EliasFleckenstein03/lua_async
[lua_async.git] / util.lua
index 852b933e85d4760ebf04f04eff1eb4d66b0b39af..3af0ffdb69aeda81dee1e18bb18160f7e8ee11a1 100644 (file)
--- a/util.lua
+++ b/util.lua
@@ -1,29 +1,58 @@
 function lua_async.yield()
-       local co = assert(coroutine.running(), "yield called outside of an async function")
-
-       setTimeout(lua_async.resume, 0, co)
+       await(Promise(function(resolve)
+               setImmediate(resolve)
+       end))
+end
 
-       coroutine.yield()
+function lua_async.sleep(ms)
+       await(Promise(function(resolve)
+               setTimeout(resolve, ms)
+       end))
 end
 
 function lua_async.kill_thread()
        coroutine.yield(true)
 end
 
-function lua_async.sleep(ms)
-       await(Promise(function(resolve)
-               setTimeout(resolve, ms)
-       end))
+function lua_async.resume(co)
+       local status, err = coroutine.resume(co)
+
+       if coroutine.status(co) == "dead" or err then
+               lua_async.limiting.unset_limit(co)
+       end
+
+       if not status then
+               error("Error (in async function): " .. err)
+       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) do
+                       next = math.min(next, timeout.time_left)
+               end
+
+               for _, interval in pairs(lua_async.intervals.pool) do
+                       next = math.min(next, interval.time_left)
+               end
+
+               if next == math.huge then
+                       return
+               end
+
+               if next > dtime then
+                       lua_async.socket.sleep(next - dtime)
+               end
        end
 end