2017-08-25 02:39:02 +08:00
|
|
|
#define SOL_CHECK_ARGUMENTS 1
|
2016-08-11 08:39:30 +08:00
|
|
|
#include <sol.hpp>
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
std::cout << "=== protected_functions example ===" << std::endl;
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|