60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package runner
|
|
|
|
import (
|
|
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(2) // Pop table and function name
|
|
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 {
|
|
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
|
|
}
|
|
}
|