From 7a9dfd47d3b2c850ad2abf33a25687557508e160 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Thu, 22 May 2025 10:31:00 -0500 Subject: [PATCH] ensure funcs get unique pointer --- functions.go | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/functions.go b/functions.go index f5d336b..0d396a8 100644 --- a/functions.go +++ b/functions.go @@ -40,31 +40,30 @@ var ( func goFunctionWrapper(L *C.lua_State) C.int { state := &State{L: L} - // Get function pointer from the first upvalue ptr := C.lua_touserdata(L, C.get_upvalue_index(1)) if ptr == nil { state.PushString("error: function pointer not found") return -1 } - // Use read-lock for better concurrency functionRegistry.RLock() fn, ok := functionRegistry.funcs[ptr] functionRegistry.RUnlock() if !ok { + // Debug logging + fmt.Printf("Function not found for pointer %p\n", ptr) state.PushString("error: function not found in registry") return -1 } - // Call the Go function return C.int(fn(state)) } // PushGoFunction wraps a Go function and pushes it onto the Lua stack func (s *State) PushGoFunction(fn GoFunction) error { - // Allocate a pointer to use as the function key - ptr := C.malloc(1) + // Allocate unique memory for each function + ptr := C.malloc(C.size_t(unsafe.Sizeof(uintptr(0)))) if ptr == nil { return fmt.Errorf("failed to allocate memory for function pointer") } @@ -74,10 +73,8 @@ func (s *State) PushGoFunction(fn GoFunction) error { functionRegistry.funcs[ptr] = fn functionRegistry.Unlock() - // Push the pointer as lightuserdata (first upvalue) + // Push the pointer as lightuserdata C.lua_pushlightuserdata(s.L, ptr) - - // Create closure with the C wrapper and the upvalue C.lua_pushcclosure(s.L, (*[0]byte)(C.goFunctionWrapper), 1) return nil