Skip to content

Commit

Permalink
Merge pull request #453 from mzki/fix-xpcall-error-in-error-handler
Browse files Browse the repository at this point in the history
Fix xpcall error in error handler
  • Loading branch information
yuin committed Nov 4, 2023
2 parents 018eaa0 + 293e22e commit 9d7d921
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
12 changes: 12 additions & 0 deletions _glua-tests/issues.lua
Expand Up @@ -457,6 +457,18 @@ function test()
assert(c == 1)
assert(type(c) == "number")
end
test()

-- issue #452
function test()
local ok, msg = pcall(function()
local ok, msg = xpcall(function() error("fn") end, function(err) error("handler") end)
assert(not ok and msg)
error("expected to reach this.")
end)
assert(not ok)
end
test()

-- issue #459
function test()
Expand Down
3 changes: 3 additions & 0 deletions _state.go
Expand Up @@ -1855,6 +1855,9 @@ func (ls *LState) PCall(nargs, nret int, errfunc *LFunction) (err error) {
err = rcv.(*ApiError)
err.(*ApiError).StackTrace = ls.stackTrace(0)
}
ls.stack.SetSp(sp)
ls.currentFrame = ls.stack.Last()
ls.reg.SetTop(base)
}
}()
ls.Call(1, 1)
Expand Down
3 changes: 3 additions & 0 deletions state.go
Expand Up @@ -2014,6 +2014,9 @@ func (ls *LState) PCall(nargs, nret int, errfunc *LFunction) (err error) {
err = rcv.(*ApiError)
err.(*ApiError).StackTrace = ls.stackTrace(0)
}
ls.stack.SetSp(sp)
ls.currentFrame = ls.stack.Last()
ls.reg.SetTop(base)
}
}()
ls.Call(1, 1)
Expand Down
22 changes: 22 additions & 0 deletions state_test.go
Expand Up @@ -291,17 +291,39 @@ func TestPCall(t *testing.T) {
}))
errorIfFalse(t, strings.Contains(err.Error(), "by handler"), "")

L.Push(L.GetGlobal("f1"))
err = L.PCall(0, 0, L.NewFunction(func(L *LState) int {
L.RaiseError("error!")
return 1
}))
errorIfFalse(t, strings.Contains(err.Error(), "error!"), "")

L.Push(L.GetGlobal("f1"))
err = L.PCall(0, 0, L.NewFunction(func(L *LState) int {
panic("panicc!")
return 1
}))
errorIfFalse(t, strings.Contains(err.Error(), "panicc!"), "")

// Issue #452, expected to be revert back to previous call stack after any error.
currentFrame, currentTop, currentSp := L.currentFrame, L.GetTop(), L.stack.Sp()
L.Push(L.GetGlobal("f1"))
err = L.PCall(0, 0, nil)
errorIfFalse(t, err != nil, "")
errorIfFalse(t, L.currentFrame == currentFrame, "")
errorIfFalse(t, L.GetTop() == currentTop, "")
errorIfFalse(t, L.stack.Sp() == currentSp, "")

currentFrame, currentTop, currentSp = L.currentFrame, L.GetTop(), L.stack.Sp()
L.Push(L.GetGlobal("f1"))
err = L.PCall(0, 0, L.NewFunction(func(L *LState) int {
L.RaiseError("error!")
return 1
}))
errorIfFalse(t, err != nil, "")
errorIfFalse(t, L.currentFrame == currentFrame, "")
errorIfFalse(t, L.GetTop() == currentTop, "")
errorIfFalse(t, L.stack.Sp() == currentSp, "")
}

func TestCoroutineApi1(t *testing.T) {
Expand Down

0 comments on commit 9d7d921

Please sign in to comment.