feat: add interval function

interval(func, time)
works exactly the same as `setInterval` in javascript
runs `func` in an interval of `time` milliseconds
pull/61/head
sammyette 2021-06-11 21:21:41 -04:00
parent fe3df8c66e
commit 1e1662a6b2
No known key found for this signature in database
GPG Key ID: 50EE40A2809851F5
1 changed files with 31 additions and 0 deletions

31
lua.go
View File

@ -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
}