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>
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
int main() {
|
2018-03-16 05:16:28 +08:00
|
|
|
std::cout << "=== protected_functions ===" << std::endl;
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
sol::state lua;
|
2017-04-21 04:22:35 +08:00
|
|
|
lua.open_libraries(sol::lib::base);
|
2016-08-11 08:39:30 +08: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-10 11:27:49 +08:00
|
|
|
sol::protected_function f(lua["f"], lua["handler"]);
|
2016-08-11 08:39:30 +08:00
|
|
|
|
|
|
|
sol::protected_function_result result = f(-500);
|
|
|
|
if (result.valid()) {
|
|
|
|
// Call succeeded
|
|
|
|
int x = result;
|
2016-08-23 10:45:06 +08:00
|
|
|
std::cout << "call succeeded, result is " << x << std::endl;
|
2016-08-11 08:39:30 +08:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// Call failed
|
|
|
|
sol::error err = result;
|
|
|
|
std::string what = err.what();
|
2016-08-23 10:45:06 +08:00
|
|
|
std::cout << "call failed, sol::error::what() is " << what << std::endl;
|
2016-08-11 08:39:30 +08:00
|
|
|
// 'what' Should read
|
|
|
|
// "Handled this message: negative number detected"
|
|
|
|
}
|
|
|
|
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|