From 7f62c1fd66ffeb7e46127e5972d814abb9299848 Mon Sep 17 00:00:00 2001 From: unwox Date: Fri, 25 Oct 2024 17:33:56 +0600 Subject: implement non-blocking IO operations --- luajit.go | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) (limited to 'luajit.go') diff --git a/luajit.go b/luajit.go index 1a8b47d..9414787 100644 --- a/luajit.go +++ b/luajit.go @@ -32,10 +32,13 @@ import ( "unsafe" ) -type LuaRef C.longlong +type LuaRef C.int // Lua is a wrapper around C Lua state with several conveniences. type Lua struct { l *C.lua_State + running **Lua + yield func() + resume func() bool } //export luna_run_go_func @@ -48,6 +51,7 @@ func luna_run_go_func(f C.uintptr_t) C.int { // Start opens the Lua context with all built-in libraries. func (l *Lua) Start() { l.l = C.luaL_newstate() + l.running = &l C.luaL_openlibs(l.l) } @@ -73,6 +77,7 @@ func (l *Lua) Require(file string) error { // PCall calls a function with the stack index (-nargs-1) expecting nresults // number of results. func (l *Lua) PCall(nargs int, nresults int) error { + *l.running = l res := C.lua_pcall(l.l, C.int(nargs), C.int(nresults), 0) if res != C.LUA_OK { errMsg := l.ToString(-1) @@ -128,6 +133,8 @@ func (l *Lua) PushNil() { // PushBoolean pushes a boolean onto the Lua stack. func (l *Lua) PushBoolean(b bool) { + // For some reason this is needed here to not mess up threads. + *l.running = l if b { C.lua_pushboolean(l.l, 1) } else { @@ -157,7 +164,7 @@ func (l *Lua) PushString(str string) { // method later. func (l *Lua) PushGoFunction(f func (l *Lua) int) cgo.Handle { h := cgo.NewHandle(func () int { - return f(l) + return f(*l.running) }) C.luna_push_function(l.l, C.uintptr_t(h)) return h @@ -448,7 +455,15 @@ func (l *Lua) GetGlobal(name string) { C.lua_getfield(l.l, C.LUA_GLOBALSINDEX, cstr) } -func (l *Lua) Error(msg string) { - l.PushString(msg) - C.lua_error(l.l) +func (l *Lua) NewThread(yield func(), resume func() bool) *Lua { + return &Lua{ + l: C.lua_newthread(l.l), + running: l.running, + resume: resume, + yield: yield, + } +} + +func (l *Lua) Unref(ref LuaRef) { + C.luaL_unref(l.l, C.LUA_REGISTRYINDEX, C.int(ref)) } -- cgit v1.2.3