package runner import ( "Moonshark/core/utils/logger" luajit "git.sharkk.net/Sky/LuaJIT-to-Go" ) // ModuleFunc is a function that returns a map of module functions type ModuleFunc func() map[string]luajit.GoFunction // RegisterModule registers a map of functions as a Lua module func RegisterModule(state *luajit.State, name string, funcs map[string]luajit.GoFunction) error { // Create a new table for the module state.NewTable() // Add each function to the module table for fname, f := range funcs { // Push function name state.PushString(fname) // Push function if err := state.PushGoFunction(f); err != nil { state.Pop(1) // Pop table return err } // Set table[fname] = f state.SetTable(-3) } // Register the module globally state.SetGlobal(name) return nil } // ModuleInitFunc creates a state initializer that registers multiple modules func ModuleInitFunc(modules map[string]ModuleFunc) StateInitFunc { return func(state *luajit.State) error { for name, moduleFunc := range modules { if err := RegisterModule(state, name, moduleFunc()); err != nil { logger.Error("Failed to register module %s: %v", name, err) return err } } return nil } } // CombineInitFuncs combines multiple state initializer functions into one func CombineInitFuncs(funcs ...StateInitFunc) StateInitFunc { return func(state *luajit.State) error { for _, f := range funcs { if f != nil { if err := f(state); err != nil { return err } } } return nil } } // RegisterLuaCode registers a Lua code snippet as a module func RegisterLuaCode(state *luajit.State, code string) error { return state.DoString(code) } // RegisterLuaCodeInitFunc returns a StateInitFunc that registers Lua code func RegisterLuaCodeInitFunc(code string) StateInitFunc { return func(state *luajit.State) error { return RegisterLuaCode(state, code) } } // RegisterLuaModuleInitFunc returns a StateInitFunc that registers a Lua module func RegisterLuaModuleInitFunc(name string, code string) StateInitFunc { return func(state *luajit.State) error { // Create name = {} global state.NewTable() state.SetGlobal(name) // Then run the module code which will populate it return state.DoString(code) } }