aboutsummaryrefslogtreecommitdiff
path: root/limiting.lua
diff options
context:
space:
mode:
authorElias Fleckenstein <eliasfleckenstein@web.de>2021-08-06 19:19:23 +0200
committerElias Fleckenstein <eliasfleckenstein@web.de>2021-08-06 19:19:23 +0200
commita2770298f040307f8dd59c7a88d7e40d37faec14 (patch)
tree3ce0ec0c31be5b2f87c086488973e8957acf84ad /limiting.lua
parentf6cc945b08e5a89492d92a88a7146da421e42819 (diff)
downloadlua_async-a2770298f040307f8dd59c7a88d7e40d37faec14.tar.xz
Add source code
Diffstat (limited to 'limiting.lua')
-rw-r--r--limiting.lua37
1 files changed, 37 insertions, 0 deletions
diff --git a/limiting.lua b/limiting.lua
new file mode 100644
index 0000000..d5df448
--- /dev/null
+++ b/limiting.lua
@@ -0,0 +1,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 = os.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 os.clock() >= limit.next_yield then
+ lua_async.yield()
+ limit.next_yield = os.clock() + limit.limit
+ return true
+ end
+
+ return false
+end
+