| 5 | #include <iostream> |
| 6 | |
| 7 | int main(int, char*[]) { |
| 8 | std::cout << "=== running lua code (safely) ===" |
| 9 | << std::endl; |
| 10 | |
| 11 | { |
| 12 | std::ofstream out("a_lua_script.lua"); |
| 13 | out << "print('hi from a lua script file')"; |
| 14 | } |
| 15 | |
| 16 | sol::state lua; |
| 17 | lua.open_libraries(sol::lib::base); |
| 18 | |
| 19 | // load and execute from string |
| 20 | auto result = lua.safe_script( |
| 21 | "a = 'test'", sol::script_pass_on_error); |
| 22 | if (!result.valid()) { |
| 23 | sol::error err = result; |
| 24 | std::cerr << "The code has failed to run!\n" |
| 25 | << err.what() << "\nPanicking and exiting..." |
| 26 | << std::endl; |
| 27 | return 1; |
| 28 | } |
| 29 | |
| 30 | // load and execute from file |
| 31 | auto script_from_file_result = lua.safe_script_file( |
| 32 | "a_lua_script.lua", sol::script_pass_on_error); |
| 33 | if (!script_from_file_result.valid()) { |
| 34 | sol::error err = script_from_file_result; |
| 35 | std::cerr |
| 36 | << "The code from the file has failed to run!\n" |
| 37 | << err.what() << "\nPanicking and exiting..." |
| 38 | << std::endl; |
| 39 | return 1; |
| 40 | } |
| 41 | |
| 42 | // run a script, get the result |
| 43 | sol::optional<int> maybe_value = lua.safe_script( |
| 44 | "return 54", sol::script_pass_on_error); |
| 45 | SOL_ASSERT(maybe_value.has_value()); |
| 46 | SOL_ASSERT(*maybe_value == 54); |
| 47 | |
| 48 | auto bad_code_result = lua.safe_script( |
| 49 | "123 herp.derp", sol::script_pass_on_error); |
| 50 | SOL_ASSERT(!bad_code_result.valid()); |
| 51 | |
| 52 | // you can also specify a handler function, and it'll |
| 53 | // properly work here |
| 54 | auto bad_code_result2 = lua.script("123 herp.derp", |
| 55 | [](lua_State*, sol::protected_function_result pfr) { |
| 56 | // pfr will contain things that went wrong, for |
| 57 | // either loading or executing the script Can |
| 58 | // throw your own custom error You can also just |
| 59 | // return it, and let the call-site handle the |
| 60 | // error if necessary. |
| 61 | return pfr; |
| 62 | }); |
| 63 | // it did not work |
| 64 | SOL_ASSERT(!bad_code_result2.valid()); |
nothing calls this directly
no test coverage detected