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

Function main

examples/source/error_handler.cpp:6–83  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main() {
7
8 const auto& code = R"(
9 bark_power = 11;
10
11 function got_problems( error_msg )
12 return "got_problems handler: " .. error_msg
13 end
14
15 function woof ( bark_energy )
16 if bark_energy < 20 then
17 error("*whine*")
18 end
19 return (bark_energy * (bark_power / 4))
20 end
21
22 function woofers ( bark_energy )
23 if bark_energy < 10 then
24 error("*whine*")
25 end
26 return (bark_energy * (bark_power / 4))
27 end
28 )";
29
30 sol::state lua;
31 lua.open_libraries(sol::lib::base);
32
33 lua.script(code);
34
35 sol::protected_function problematic_woof = lua["woof"];
36 problematic_woof.set_error_handler(lua["got_problems"]);
37
38 auto firstwoof = problematic_woof(20);
39 if (firstwoof.valid()) {
40 // Can work with contents
41 double numwoof = firstwoof;
42 std::cout << "Got value: " << numwoof << std::endl;
43 }
44 else {
45 // An error has occured
46 sol::error err = firstwoof;
47 std::string what = err.what();
48 std::cout << what << std::endl;
49 }
50
51 // errors, calls handler and then returns a string error
52 // from Lua at the top of the stack
53 auto secondwoof = problematic_woof(19);
54 if (secondwoof.valid()) {
55 // Call succeeded
56 double numwoof = secondwoof;
57 std::cout << "Got value: " << numwoof << std::endl;
58 }
59 else {
60 // Call failed
61 // Note that if the handler was successfully called,
62 // this will include the additional appended error
63 // message information of "got_problems handler: " ...

Callers

nothing calls this directly

Calls 6

open_librariesMethod · 0.80
scriptMethod · 0.80
whatMethod · 0.80
set_error_handlerMethod · 0.45
validMethod · 0.45
valueMethod · 0.45

Tested by

no test coverage detected