mirror of https://github.com/Hilbis/Hilbish
feat: add interval function
interval(func, time) works exactly the same as `setInterval` in javascript runs `func` in an interval of `time` millisecondspull/61/head
parent
fe3df8c66e
commit
1e1662a6b2
31
lua.go
31
lua.go
|
@ -34,6 +34,7 @@ func LuaInit() {
|
||||||
l.SetGlobal("exec", l.NewFunction(hshexec))
|
l.SetGlobal("exec", l.NewFunction(hshexec))
|
||||||
l.SetGlobal("goro", luar.New(l, hshgoroutine))
|
l.SetGlobal("goro", luar.New(l, hshgoroutine))
|
||||||
l.SetGlobal("timeout", luar.New(l, hshtimeout))
|
l.SetGlobal("timeout", luar.New(l, hshtimeout))
|
||||||
|
l.SetGlobal("interval", l.NewFunction(hshinterval))
|
||||||
|
|
||||||
// yes this is stupid, i know
|
// yes this is stupid, i know
|
||||||
l.PreloadModule("hilbish", HilbishLoader)
|
l.PreloadModule("hilbish", HilbishLoader)
|
||||||
|
@ -159,3 +160,33 @@ func hshtimeout(timeoutfunc func(), ms int) {
|
||||||
time.AfterFunc(timeout, timeoutfunc)
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue