MCPcopy Create free account
hub / github.com/ThePhD/sol2 / main

Function main

examples/source/protected_functions.cpp:6–49  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main() {
7 std::cout << "=== protected_functions ===" << std::endl;
8
9 sol::state lua;
10 lua.open_libraries(sol::lib::base);
11
12 // A complicated function which can error out
13 // We define both in terms of Lua code
14
15 lua.script(R"(
16 function handler (message)
17 return "Handled this message: " .. message
18 end
19
20 function f (a)
21 if a < 0 then
22 error("negative number detected")
23 end
24 return a + 5
25 end
26 )");
27
28 // Get a protected function out of Lua
29 sol::protected_function f(lua["f"], lua["handler"]);
30
31 sol::protected_function_result result = f(-500);
32 if (result.valid()) {
33 // Call succeeded
34 int x = result;
35 std::cout << "call succeeded, result is " << x
36 << std::endl;
37 }
38 else {
39 // Call failed
40 sol::error err = result;
41 std::string what = err.what();
42 std::cout << "call failed, sol::error::what() is "
43 << what << std::endl;
44 // 'what' Should read
45 // "Handled this message: negative number detected"
46 }
47
48 std::cout << std::endl;
49}

Callers

nothing calls this directly

Calls 4

open_librariesMethod · 0.80
scriptMethod · 0.80
whatMethod · 0.80
validMethod · 0.45

Tested by

no test coverage detected