2019-05-21 19:17:31 -04:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-27 22:27:38 -07:00
|
|
|
#include <sol/sol.hpp>
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
int main() {
|
2018-03-15 17:16:28 -04:00
|
|
|
std::cout << "=== protected_functions ===" << std::endl;
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
sol::state lua;
|
2017-04-20 22:22:35 +02:00
|
|
|
lua.open_libraries(sol::lib::base);
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
// A complicated function which can error out
|
|
|
|
// We define both in terms of Lua code
|
|
|
|
|
|
|
|
lua.script(R"(
|
|
|
|
function handler (message)
|
|
|
|
return "Handled this message: " .. message
|
|
|
|
end
|
|
|
|
|
|
|
|
function f (a)
|
|
|
|
if a < 0 then
|
|
|
|
error("negative number detected")
|
|
|
|
end
|
|
|
|
return a + 5
|
|
|
|
end
|
|
|
|
)");
|
|
|
|
|
|
|
|
// Get a protected function out of Lua
|
2018-03-09 22:27:49 -05:00
|
|
|
sol::protected_function f(lua["f"], lua["handler"]);
|
2016-08-10 20:39:30 -04:00
|
|
|
|
|
|
|
sol::protected_function_result result = f(-500);
|
|
|
|
if (result.valid()) {
|
|
|
|
// Call succeeded
|
|
|
|
int x = result;
|
2021-03-06 10:14:48 -05:00
|
|
|
std::cout << "call succeeded, result is " << x
|
|
|
|
<< std::endl;
|
2016-08-10 20:39:30 -04:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// Call failed
|
|
|
|
sol::error err = result;
|
|
|
|
std::string what = err.what();
|
2021-03-06 10:14:48 -05:00
|
|
|
std::cout << "call failed, sol::error::what() is "
|
|
|
|
<< what << std::endl;
|
2021-03-06 01:03:23 -05:00
|
|
|
// 'what' Should read
|
2016-08-10 20:39:30 -04:00
|
|
|
// "Handled this message: negative number detected"
|
|
|
|
}
|
|
|
|
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|