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-17 04:47:09 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
int main() {
|
2018-03-17 04:47:09 +08:00
|
|
|
|
|
|
|
std::cout << "=== safe_script usage ===" << std::endl;
|
|
|
|
|
|
|
|
sol::state lua;
|
2021-03-06 23:14:48 +08:00
|
|
|
// uses sol::script_default_on_error, which either panics or
|
|
|
|
// throws, depending on your configuration and compiler
|
|
|
|
// settings
|
2018-03-17 04:47:09 +08:00
|
|
|
try {
|
|
|
|
auto result1 = lua.safe_script("bad.code");
|
|
|
|
}
|
2021-03-06 14:03:23 +08:00
|
|
|
catch (const sol::error& e) {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "an expected error has occurred: "
|
|
|
|
<< e.what() << std::endl;
|
2018-03-17 04:47:09 +08:00
|
|
|
}
|
2021-03-06 14:03:23 +08:00
|
|
|
|
2018-03-17 04:47:09 +08:00
|
|
|
// a custom handler that you write yourself
|
2021-03-06 23:14:48 +08:00
|
|
|
// is only called when an error happens with loading or
|
|
|
|
// running the script
|
|
|
|
auto result2 = lua.safe_script("123 bad.code",
|
|
|
|
[](lua_State*, sol::protected_function_result pfr) {
|
|
|
|
// pfr will contain things that went wrong, for
|
|
|
|
// either loading or executing the script the user
|
|
|
|
// can do whatever they like here, including
|
|
|
|
// throw. Otherwise...
|
|
|
|
sol::error err = pfr;
|
|
|
|
std::cout
|
|
|
|
<< "An error (an expected one) occurred: "
|
|
|
|
<< err.what() << std::endl;
|
|
|
|
|
|
|
|
// ... they need to return the
|
|
|
|
// protected_function_result
|
|
|
|
return pfr;
|
|
|
|
});
|
2018-03-17 04:47:09 +08:00
|
|
|
|
|
|
|
std::cout << std::endl;
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|