diff --git a/Source/LuaBridge/detail/Invoke.h b/Source/LuaBridge/detail/Invoke.h index 6a4415e5..3a2cfef1 100644 --- a/Source/LuaBridge/detail/Invoke.h +++ b/Source/LuaBridge/detail/Invoke.h @@ -216,7 +216,8 @@ LuaResult callWithHandler(const LuaRef& object, F&& errorHandler, Args&&... args } } - const int code = lua_pcall(L, sizeof...(Args), LUA_MULTRET, isValidHandler ? (-static_cast(sizeof...(Args)) - 2) : 0); + const int errorFunctionIndex = isValidHandler ? (-static_cast(sizeof...(Args)) - 2) : 0; + const int code = lua_pcall(L, sizeof...(Args), LUA_MULTRET, errorFunctionIndex); if (code != LUABRIDGE_LUA_OK) { auto ec = makeErrorCode(ErrorCode::LuaFunctionCallFailed); @@ -231,6 +232,9 @@ LuaResult callWithHandler(const LuaRef& object, F&& errorHandler, Args&&... args return LuaResult::errorFromStack(L, ec); } + + if constexpr (isValidHandler) + if (errorFunctionIndex) lua_remove(L, errorFunctionIndex); return LuaResult::valuesFromStack(L, stackTop); } diff --git a/Tests/Source/LuaRefTests.cpp b/Tests/Source/LuaRefTests.cpp index df4cd448..da410e77 100644 --- a/Tests/Source/LuaRefTests.cpp +++ b/Tests/Source/LuaRefTests.cpp @@ -621,6 +621,33 @@ TEST_F(LuaRefTests, CallableWithNullCFunction) #endif } +TEST_F(LuaRefTests, CallableWithIntToBoolValuedFunction) +{ + runLua("function f(x) return x <= 1 end"); + auto f = luabridge::getGlobal(L, "f"); + EXPECT_TRUE(f.isCallable()); + + bool calledHandler = false; + std::string errorMessage; + auto handler = [&](lua_State*) -> int + { + calledHandler = true; + + if (auto msg = lua_tostring(L, 1)) + errorMessage = msg; + + return 0; + }; + + auto result = f.callWithHandler(handler, 2); + EXPECT_TRUE(result); + EXPECT_FALSE(calledHandler); + EXPECT_EQ(result.size(), 1); + EXPECT_TRUE(result[0].isValid()); + EXPECT_TRUE(result[0].isBool()); + EXPECT_FALSE(result[0]); +} + TEST_F(LuaRefTests, Pop) { lua_pushstring(L, "hello");