Skip to content

added test to show call-with-handler-failure. #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: dev/improved_call_with_handler
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Source/LuaBridge/detail/Invoke.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>(sizeof...(Args)) - 2) : 0);
const int errorFunctionIndex = isValidHandler ? (-static_cast<int>(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);
Expand All @@ -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);
}
Expand Down
27 changes: 27 additions & 0 deletions Tests/Source/LuaRefTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down