From 1e1662a6b2ad282797f57ee1333f613009f1edf9 Mon Sep 17 00:00:00 2001 From: sammyette <38820196+TorchedSammy@users.noreply.github.com> Date: Fri, 11 Jun 2021 21:21:41 -0400 Subject: [PATCH] feat: add interval function interval(func, time) works exactly the same as `setInterval` in javascript runs `func` in an interval of `time` milliseconds --- lua.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/lua.go b/lua.go index 66f6fd5..58bee46 100644 --- a/lua.go +++ b/lua.go @@ -34,6 +34,7 @@ func LuaInit() { l.SetGlobal("exec", l.NewFunction(hshexec)) l.SetGlobal("goro", luar.New(l, hshgoroutine)) l.SetGlobal("timeout", luar.New(l, hshtimeout)) + l.SetGlobal("interval", l.NewFunction(hshinterval)) // yes this is stupid, i know l.PreloadModule("hilbish", HilbishLoader) @@ -159,3 +160,33 @@ func hshtimeout(timeoutfunc func(), ms int) { time.AfterFunc(timeout, timeoutfunc) } +func hshinterval(L *lua.LState) int { + intervalfunc := L.CheckFunction(1) + ms := L.CheckInt(2) + interval := time.Duration(ms) * time.Millisecond + + ticker := time.NewTicker(interval) + stop := make(chan lua.LValue) + + go func() { + for { + select { + case <-ticker.C: + if err := L.CallByParam(lua.P{ + Fn: intervalfunc, + NRet: 0, + Protect: true, + }); err != nil { + panic(err) + } + case <-stop: + ticker.Stop() + return + } + } + }() + + L.Push(lua.LChannel(stop)) + return 1 +} +