| 4 | #include <iostream> |
| 5 | |
| 6 | int main(int, char**) { |
| 7 | std::cout << "=== script error handling ===" << std::endl; |
| 8 | |
| 9 | sol::state lua; |
| 10 | |
| 11 | std::string code = R"( |
| 12 | bad&$#*$syntax |
| 13 | bad.code = 2 |
| 14 | return 24 |
| 15 | )"; |
| 16 | |
| 17 | /* OPTION 1 */ |
| 18 | // Handling code like this can be robust |
| 19 | // If you disable exceptions, then obviously you would |
| 20 | // remove the try-catch branches, and then rely on the |
| 21 | // `lua_atpanic` function being called and trapping errors |
| 22 | // there before exiting the application |
| 23 | { |
| 24 | // script_default_on_error throws / panics when the |
| 25 | // code is bad: trap the error |
| 26 | try { |
| 27 | int value = lua.script( |
| 28 | code, sol::script_default_on_error); |
| 29 | // This will never be reached |
| 30 | std::cout << value << std::endl; |
| 31 | SOL_ASSERT(value == 24); |
| 32 | } |
| 33 | catch (const sol::error& err) { |
| 34 | std::cout << "Something went horribly wrong: " |
| 35 | "thrown error" |
| 36 | << "\n\t" << err.what() << std::endl; |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /* OPTION 2 */ |
| 41 | // Use the script_pass_on_error handler |
| 42 | // this simply passes through the protected_function_result, |
| 43 | // rather than throwing it or calling panic |
| 44 | // This will check code validity and also whether or not it |
| 45 | // runs well |
| 46 | { |
| 47 | sol::protected_function_result result |
| 48 | = lua.script(code, sol::script_pass_on_error); |
| 49 | SOL_ASSERT(!result.valid()); |
| 50 | if (!result.valid()) { |
| 51 | sol::error err = result; |
| 52 | sol::call_status status = result.status(); |
| 53 | std::cout << "Something went horribly wrong: " |
| 54 | << sol::to_string(status) << " error" |
| 55 | << "\n\t" << err.what() << std::endl; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /* OPTION 3 */ |
| 60 | // This is a lower-level, more explicit way to load code |
| 61 | // This explicitly loads the code, giving you access to any |
| 62 | // errors plus the load status then, it turns the loaded |
| 63 | // code into a sol::protected_function which is then called |