| 4 | #include <iostream> |
| 5 | |
| 6 | int main() { |
| 7 | std::cout << "=== protected_functions ===" << std::endl; |
| 8 | |
| 9 | sol::state lua; |
| 10 | lua.open_libraries(sol::lib::base); |
| 11 | |
| 12 | // A complicated function which can error out |
| 13 | // We define both in terms of Lua code |
| 14 | |
| 15 | lua.script(R"( |
| 16 | function handler (message) |
| 17 | return "Handled this message: " .. message |
| 18 | end |
| 19 | |
| 20 | function f (a) |
| 21 | if a < 0 then |
| 22 | error("negative number detected") |
| 23 | end |
| 24 | return a + 5 |
| 25 | end |
| 26 | )"); |
| 27 | |
| 28 | // Get a protected function out of Lua |
| 29 | sol::protected_function f(lua["f"], lua["handler"]); |
| 30 | |
| 31 | sol::protected_function_result result = f(-500); |
| 32 | if (result.valid()) { |
| 33 | // Call succeeded |
| 34 | int x = result; |
| 35 | std::cout << "call succeeded, result is " << x |
| 36 | << std::endl; |
| 37 | } |
| 38 | else { |
| 39 | // Call failed |
| 40 | sol::error err = result; |
| 41 | std::string what = err.what(); |
| 42 | std::cout << "call failed, sol::error::what() is " |
| 43 | << what << std::endl; |
| 44 | // 'what' Should read |
| 45 | // "Handled this message: negative number detected" |
| 46 | } |
| 47 | |
| 48 | std::cout << std::endl; |
| 49 | } |
nothing calls this directly
no test coverage detected