81 lines
2.1 KiB
Go
81 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"Moonshark/registry"
|
|
|
|
luajit "git.sharkk.net/Sky/LuaJIT-to-Go"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fmt.Fprintf(os.Stderr, "Usage: %s <script.lua>\n", filepath.Base(os.Args[0]))
|
|
os.Exit(1)
|
|
}
|
|
|
|
scriptPath := os.Args[1]
|
|
|
|
// Check if file exists
|
|
if _, err := os.Stat(scriptPath); os.IsNotExist(err) {
|
|
fmt.Fprintf(os.Stderr, "Error: script file '%s' not found\n", scriptPath)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Initialize global registry
|
|
if err := registry.Initialize(); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to initialize registry: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Create new Lua state with standard libraries
|
|
state := luajit.New()
|
|
if state == nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to create Lua state\n")
|
|
os.Exit(1)
|
|
}
|
|
defer state.Close()
|
|
|
|
// Install module system in main state
|
|
if err := registry.Global.InstallInState(state); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to install module system: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Get the absolute path to the script directory
|
|
scriptDir := filepath.Dir(scriptPath)
|
|
absScriptDir, err := filepath.Abs(scriptDir)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error: failed to get absolute path: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Add script directory to Lua's package.path
|
|
packagePath := filepath.Join(absScriptDir, "?.lua")
|
|
if err := state.AddPackagePath(packagePath); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Warning: failed to add script directory to package.path: %v\n", err)
|
|
}
|
|
|
|
// Read script file
|
|
scriptContent, err := os.ReadFile(scriptPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error reading script file '%s': %v\n", scriptPath, err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Compile script to bytecode
|
|
bytecode, err := state.CompileBytecode(string(scriptContent), scriptPath)
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error compiling '%s': %v\n", scriptPath, err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Execute the compiled bytecode
|
|
if err := state.LoadAndRunBytecode(bytecode, scriptPath); err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error executing '%s': %v\n", scriptPath, err)
|
|
os.Exit(1)
|
|
}
|
|
}
|