aboutsummaryrefslogtreecommitdiff
path: root/limiting.lua
blob: 394006de1d37a273ab8ed5fb1275d65df31745a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
lua_async.limiting = {
	pool = {},
}

function lua_async.limiting.unset_limit(co)
	lua_async.limiting.pool[co] = nil
end

function lua_async.set_limit(ms)
	local co = assert(coroutine.running(), "set_limit called outside of an async function")

	local limit = ms / 1000

	lua_async.limiting.pool[co] = {
		limit = limit,
		next_yield = lua_async.clock() + limit,
	}
end

function lua_async.unset_limit()
	local co = assert(coroutine.running(), "unset_limit called outside of an async function")
	lua_async.limiting.unset_limit(co)
end

function lua_async.check_limit()
	local co = assert(coroutine.running(), "check_limit called outside of an async function")
	local limit = lua_async.limiting.pool[co]

	if limit and lua_async.clock() >= limit.next_yield then
		lua_async.yield()
		limit.next_yield = lua_async.clock() + limit.limit
		return true
	end

	return false
end