]> git.lizzy.rs Git - lua_async.git/blob - limiting.lua
Merge branch 'master' of https://github.com/EliasFleckenstein03/lua_async
[lua_async.git] / limiting.lua
1 lua_async.limiting = {
2         pool = {},
3 }
4
5 function lua_async.limiting.unset_limit(co)
6         lua_async.limiting.pool[co] = nil
7 end
8
9 function lua_async.set_limit(ms)
10         local co = assert(coroutine.running(), "set_limit called outside of an async function")
11
12         local limit = ms / 1000
13
14         lua_async.limiting.pool[co] = {
15                 limit = limit,
16                 next_yield = lua_async.clock() + limit,
17         }
18 end
19
20 function lua_async.unset_limit()
21         local co = assert(coroutine.running(), "unset_limit called outside of an async function")
22         lua_async.limiting.unset_limit(co)
23 end
24
25 function lua_async.check_limit()
26         local co = assert(coroutine.running(), "check_limit called outside of an async function")
27         local limit = lua_async.limiting.pool[co]
28
29         if limit and lua_async.clock() >= limit.next_yield then
30                 lua_async.yield()
31                 limit.next_yield = lua_async.clock() + limit.limit
32                 return true
33         end
34
35         return false
36 end
37