diff options
Diffstat (limited to 'lua.go')
| -rw-r--r-- | lua.go | 28 |
1 files changed, 23 insertions, 5 deletions
@@ -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) } @@ -72,6 +76,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_pcallk(l.l, C.int(nargs), C.int(nresults), 0, 0, nil) if res != C.LUA_OK { errMsg := l.ToString(-1) @@ -132,6 +137,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 { @@ -161,7 +168,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 @@ -200,6 +207,9 @@ func (l *Lua) PushAny(v any) error { case float64: v, _ := v.(float64) l.PushFloatNumber(v) + case bool: + v, _ := v.(bool) + l.PushBoolean(v) case map[string]any: v, _ := v.(map[string]any) err := l.PushObject(v) @@ -453,7 +463,15 @@ func (l *Lua) GetGlobal(name string) { C.lua_getglobal(l.l, 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)) } |
