| 5 | #include <iostream> |
| 6 | |
| 7 | int my_exception_handler(lua_State* L, |
| 8 | sol::optional<const std::exception&> maybe_exception, |
| 9 | sol::string_view description) { |
| 10 | // L is the lua state, which you can wrap in a state_view if |
| 11 | // necessary maybe_exception will contain exception, if it |
| 12 | // exists description will either be the what() of the |
| 13 | // exception or a description saying that we hit the |
| 14 | // general-case catch(...) |
| 15 | std::cout << "An exception occurred in a function, here's " |
| 16 | "what it says "; |
| 17 | if (maybe_exception) { |
| 18 | std::cout << "(straight from the exception): "; |
| 19 | const std::exception& ex = *maybe_exception; |
| 20 | std::cout << ex.what() << std::endl; |
| 21 | } |
| 22 | else { |
| 23 | std::cout << "(from the description parameter): "; |
| 24 | std::cout.write(description.data(), |
| 25 | static_cast<std::streamsize>(description.size())); |
| 26 | std::cout << std::endl; |
| 27 | } |
| 28 | |
| 29 | // you must push 1 element onto the stack to be |
| 30 | // transported through as the error object in Lua |
| 31 | // note that Lua -- and 99.5% of all Lua users and libraries |
| 32 | // -- expects a string so we push a single string (in our |
| 33 | // case, the description of the error) |
| 34 | return sol::stack::push(L, description); |
| 35 | } |
| 36 | |
| 37 | void will_throw() { |
| 38 | throw std::runtime_error("oh no not an exception!!!"); |