package runner import ( _ "embed" "sync" "sync/atomic" "Moonshark/core/utils/logger" luajit "git.sharkk.net/Sky/LuaJIT-to-Go" ) //go:embed sandbox.lua var sandboxLuaCode string // Global bytecode cache to improve performance var ( sandboxBytecode atomic.Pointer[[]byte] bytecodeOnce sync.Once ) // precompileSandboxCode compiles the sandbox.lua code to bytecode once func precompileSandboxCode() { // Create temporary state for compilation tempState := luajit.New() if tempState == nil { logger.ErrorCont("Failed to create temp Lua state for bytecode compilation") return } defer tempState.Close() defer tempState.Cleanup() code, err := tempState.CompileBytecode(sandboxLuaCode, "sandbox.lua") if err != nil { logger.ErrorCont("Failed to compile sandbox code: %v", err) return } bytecode := make([]byte, len(code)) copy(bytecode, code) sandboxBytecode.Store(&bytecode) logger.ServerCont("Successfully precompiled sandbox.lua to bytecode (%d bytes)", len(code)) } // loadSandboxIntoState loads the sandbox code into a Lua state func loadSandboxIntoState(state *luajit.State, verbose bool) error { bytecodeOnce.Do(precompileSandboxCode) bytecode := sandboxBytecode.Load() if bytecode != nil && len(*bytecode) > 0 { if verbose { logger.ServerCont("Loading sandbox.lua from precompiled bytecode") // piggyback off Sandbox.go's Setup() } return state.LoadAndRunBytecode(*bytecode, "sandbox.lua") } // Fallback to direct execution if verbose { logger.WarningCont("Using non-precompiled sandbox.lua (bytecode compilation failed)") } return state.DoString(sandboxLuaCode) }