summaryrefslogtreecommitdiff
path: root/luajit.go
diff options
context:
space:
mode:
authorunwox <me@unwox.com>2024-10-25 17:33:56 +0600
committerunwox <me@unwox.com>2024-11-12 10:27:12 +0600
commit7f62c1fd66ffeb7e46127e5972d814abb9299848 (patch)
tree710094f851143dfd5e8b385c8ac078de4495f76b /luajit.go
parent41ba7127063d65638ae2ec1941f737e9d3426ef3 (diff)
implement non-blocking IO operations
Diffstat (limited to 'luajit.go')
-rw-r--r--luajit.go25
1 files changed, 20 insertions, 5 deletions
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))
}