feat: implement hilbish.interval

lua5.4
TorchedSammy 2022-03-29 13:05:43 -04:00
parent 10f6db20d4
commit 7373718416
Signed by: sammyette
GPG Key ID: 904FC49417B44DCD
1 changed files with 22 additions and 16 deletions

38
api.go
View File

@ -4,13 +4,13 @@
package main package main
import ( import (
// "fmt" "fmt"
"os" "os"
// "os/exec" // "os/exec"
"runtime" "runtime"
"strings" "strings"
// "syscall" // "syscall"
// "time" "time"
"hilbish/util" "hilbish/util"
@ -40,8 +40,8 @@ var exports = map[string]util.LuaExport{
"prompt": util.LuaExport{hlprompt, 1, false}, "prompt": util.LuaExport{hlprompt, 1, false},
/* /*
"inputMode": hlinputMode, "inputMode": hlinputMode,
"interval": hlinterval,
*/ */
"interval": util.LuaExport{hlinterval, 2, false},
"read": util.LuaExport{hlprompt, 1, false}, "read": util.LuaExport{hlprompt, 1, false},
/* /*
"run": hlrun, "run": hlrun,
@ -411,30 +411,37 @@ func hltimeout(L *lua.LState) int {
} }
return 0 return 0
} }
*/
// interval(cb, time) // interval(cb, time)
// Runs the `cb` function every `time` milliseconds // Runs the `cb` function every `time` milliseconds
// --- @param cb function // --- @param cb function
// --- @param time number // --- @param time number
func hlinterval(L *lua.LState) int { func hlinterval(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
intervalfunc := L.CheckFunction(1) if err := c.CheckNArgs(2); err != nil {
ms := L.CheckInt(2) return nil, err
}
cb, err := c.ClosureArg(0)
if err != nil {
return nil, err
}
ms, err := c.IntArg(1)
if err != nil {
return nil, err
}
interval := time.Duration(ms) * time.Millisecond interval := time.Duration(ms) * time.Millisecond
ticker := time.NewTicker(interval) ticker := time.NewTicker(interval)
stop := make(chan lua.LValue) stop := make(chan rt.Value)
go func() { go func() {
for { for {
select { select {
case <-ticker.C: case <-ticker.C:
if err := L.CallByParam(lua.P{ _, err := rt.Call1(l.MainThread(), rt.FunctionValue(cb))
Fn: intervalfunc, if err != nil {
NRet: 0,
Protect: true,
}); err != nil {
fmt.Fprintln(os.Stderr, "Error in interval function:\n\n", err) fmt.Fprintln(os.Stderr, "Error in interval function:\n\n", err)
stop <- lua.LTrue // stop the interval stop <- rt.BoolValue(true) // stop the interval
} }
case <-stop: case <-stop:
ticker.Stop() ticker.Stop()
@ -443,10 +450,9 @@ func hlinterval(L *lua.LState) int {
} }
}() }()
L.Push(lua.LChannel(stop)) // TODO: return channel
return 1 return c.Next(), nil
} }
*/
// complete(scope, cb) // complete(scope, cb)
// Registers a completion handler for `scope`. // Registers a completion handler for `scope`.