diff --git a/lib/lua/vm.ex b/lib/lua/vm.ex index 6b22c1b..80184d9 100644 --- a/lib/lua/vm.ex +++ b/lib/lua/vm.ex @@ -16,9 +16,10 @@ defmodule Lua.VM do """ @spec execute(Prototype.t(), State.t()) :: {:ok, list(), State.t()} def execute(%Prototype{} = proto, state \\ State.new()) do - # Create register file - tuple of nils - # For now, just allocate 256 registers (we'll optimize this later) - registers = Tuple.duplicate(nil, 256) + # Create register file sized to the prototype's needs. + # The +16 buffer covers multi-return expansion slots that the codegen doesn't + # always track in max_registers (call results can land beyond the stated max). + registers = Tuple.duplicate(nil, proto.max_registers + 16) # Execute the prototype instructions {results, _final_regs, final_state} = diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index 47e31b0..70ab0b6 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -32,7 +32,7 @@ defmodule Lua.VM.Executor do @spec call_function(term(), list(), State.t()) :: {list(), State.t()} def call_function({:lua_closure, callee_proto, callee_upvalues}, args, state) do callee_regs = - Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 64) + Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 16) callee_regs = args @@ -499,7 +499,7 @@ defmodule Lua.VM.Executor do # Create new register file for the callee callee_regs = - Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 64) + Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 16) # Copy arguments into callee registers (params are R[0..N-1]) callee_regs = @@ -1104,7 +1104,7 @@ defmodule Lua.VM.Executor do # Helper: call a function value inline (used by generic_for) defp call_value({:lua_closure, callee_proto, callee_upvalues}, args, _proto, state) do callee_regs = - Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 64) + Tuple.duplicate(nil, max(callee_proto.max_registers, callee_proto.param_count) + 16) callee_regs = args