71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fmt.Println("Usage: go run main.go script.lua")
|
|
os.Exit(1)
|
|
}
|
|
|
|
scriptPath := os.Args[1]
|
|
|
|
// Create a new Lua state
|
|
L := luajit.New()
|
|
if L == nil {
|
|
log.Fatal("Failed to create Lua state")
|
|
}
|
|
defer L.Close()
|
|
|
|
// Register a Go function to be called from Lua
|
|
L.RegisterGoFunction("printFromGo", func(s *luajit.State) int {
|
|
msg := s.ToString(1) // Get first argument
|
|
fmt.Printf("Go received from Lua: %s\n", msg)
|
|
|
|
// Return a value to Lua
|
|
s.PushString("Hello from Go!")
|
|
return 1 // Number of return values
|
|
})
|
|
|
|
// Add some values to the Lua environment
|
|
L.PushValue(map[string]interface{}{
|
|
"appName": "LuaJIT Example",
|
|
"version": 1.0,
|
|
"features": []float64{1, 2, 3},
|
|
})
|
|
L.SetGlobal("config")
|
|
|
|
// Get the directory of the script to properly handle requires
|
|
dir := filepath.Dir(scriptPath)
|
|
L.AddPackagePath(filepath.Join(dir, "?.lua"))
|
|
|
|
// Execute the script
|
|
fmt.Printf("Running Lua script: %s\n", scriptPath)
|
|
if err := L.DoFile(scriptPath); err != nil {
|
|
log.Fatalf("Error executing script: %v", err)
|
|
}
|
|
|
|
// Call a Lua function and get its result
|
|
L.GetGlobal("getResult")
|
|
if L.IsFunction(-1) {
|
|
if err := L.Call(0, 1); err != nil {
|
|
log.Fatalf("Error calling Lua function: %v", err)
|
|
}
|
|
|
|
result, err := L.ToValue(-1)
|
|
if err != nil {
|
|
log.Fatalf("Error converting Lua result: %v", err)
|
|
}
|
|
|
|
fmt.Printf("Result from Lua: %v\n", result)
|
|
L.Pop(1) // Clean up the result
|
|
}
|
|
}
|