2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2018-03-10 11:27:49 +08:00
|
|
|
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
2021-03-06 23:14:48 +08:00
|
|
|
int my_exception_handler(lua_State* L,
|
|
|
|
sol::optional<const std::exception&> maybe_exception,
|
|
|
|
sol::string_view description) {
|
|
|
|
// L is the lua state, which you can wrap in a state_view if
|
|
|
|
// necessary maybe_exception will contain exception, if it
|
|
|
|
// exists description will either be the what() of the
|
|
|
|
// exception or a description saying that we hit the
|
|
|
|
// general-case catch(...)
|
|
|
|
std::cout << "An exception occurred in a function, here's "
|
|
|
|
"what it says ";
|
2018-03-10 11:27:49 +08:00
|
|
|
if (maybe_exception) {
|
|
|
|
std::cout << "(straight from the exception): ";
|
|
|
|
const std::exception& ex = *maybe_exception;
|
|
|
|
std::cout << ex.what() << std::endl;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
std::cout << "(from the description parameter): ";
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout.write(description.data(),
|
|
|
|
static_cast<std::streamsize>(description.size()));
|
2018-03-10 11:27:49 +08:00
|
|
|
std::cout << std::endl;
|
|
|
|
}
|
|
|
|
|
2020-12-17 04:25:35 +08:00
|
|
|
// you must push 1 element onto the stack to be
|
2018-03-10 11:27:49 +08:00
|
|
|
// transported through as the error object in Lua
|
2021-03-06 23:14:48 +08:00
|
|
|
// note that Lua -- and 99.5% of all Lua users and libraries
|
|
|
|
// -- expects a string so we push a single string (in our
|
|
|
|
// case, the description of the error)
|
2018-03-10 11:27:49 +08:00
|
|
|
return sol::stack::push(L, description);
|
|
|
|
}
|
|
|
|
|
|
|
|
void will_throw() {
|
2018-03-10 12:32:03 +08:00
|
|
|
throw std::runtime_error("oh no not an exception!!!");
|
2018-03-10 11:27:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== exception_handler ===" << std::endl;
|
2018-03-10 11:27:49 +08:00
|
|
|
|
|
|
|
sol::state lua;
|
|
|
|
lua.open_libraries(sol::lib::base);
|
|
|
|
lua.set_exception_handler(&my_exception_handler);
|
|
|
|
|
|
|
|
lua.set_function("will_throw", &will_throw);
|
|
|
|
|
2021-03-06 23:14:48 +08:00
|
|
|
sol::protected_function_result pfr = lua.safe_script(
|
|
|
|
"will_throw()", &sol::script_pass_on_error);
|
2018-03-10 11:27:49 +08:00
|
|
|
|
2022-09-28 13:56:26 +08:00
|
|
|
SOL_ASSERT(!pfr.valid());
|
2020-12-17 04:25:35 +08:00
|
|
|
|
2018-03-10 11:27:49 +08:00
|
|
|
sol::error err = pfr;
|
|
|
|
std::cout << err.what() << std::endl;
|
|
|
|
|
|
|
|
std::cout << std::endl;
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|