Skip to content

pcall discards state mutations made before error() (diverges from reference Lua) #331

Closed

Description

@davydog187

Summary

When a function called via pcall raises an error, any state mutations made before the error() call are rolled back. Reference Lua keeps those mutations; pcall only traps the error and returns false, err without unwinding side effects.

Reproduction

Mix.install([{:lua, "~> 1.0.0-rc.1"}])

code = """
x = 1
local ok, err = pcall(function()
  x = 2
  error("boom")
end)
return x, ok, err
"""

{results, _lua} = Lua.eval!(Lua.new(), code)
IO.inspect(results)

Actual: [1, false, "boom"]
Expected: [2, false, "boom"]

Reference Lua 5.x for comparison:

$ lua -e 'x = 1; pcall(function() x = 2; error("boom") end); print(x)'
2

Why this matters

Standard Lua code routinely relies on this:

  • Counters incremented before a failed call (step = step + 1; risky())
  • Partial progress recorded for retry/resume logic
  • "Mutate then validate, error on bad result" patterns
  • Logging or audit trail writes inside the protected block

All of these silently lose their effects.

Root cause

In lib/lua.ex, do_call_function/3's rescue clause returns the original state parameter rather than the partially-mutated state accumulated during execution:

defp do_call_function({:lua_closure, proto, upvalues}, args, state) do
  ...
  {results, _regs, new_state} =
    Executor.execute(proto.instructions, callee_regs, upvalues, proto, state)

  {:ok, results, new_state}
rescue
  e -> {:error, Exception.message(e), state}   # <- should thread out the partial new_state
end

The same pattern repeats in the :native_func and :compiled_closure clauses. To match reference Lua, the executor needs to thread the mutated state out through the raise (e.g., attach it to a struct exception) so the rescue can return {:error, msg, partial_state} instead of the pre-call snapshot.

Reproducible on

lua v1.0.0-rc.1 (also v1.0.0-rc.0).

Activity

  1. added 2 commits that reference this issue on Jun 4, 2026
    48c98f7
    44ec492
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions