File: state_script_safe.cpp

package info (click to toggle)
sol2 3.5.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 23,096 kB
  • sloc: cpp: 43,816; ansic: 1,018; python: 356; sh: 288; makefile: 202
file content (44 lines) | stat: -rw-r--r-- 1,230 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {

	std::cout << "=== safe_script usage ===" << std::endl;

	sol::state lua;
	// uses sol::script_default_on_error, which either panics or
	// throws, depending on your configuration and compiler
	// settings
	try {
		auto result1 = lua.safe_script("bad.code");
	}
	catch (const sol::error& e) {
		std::cout << "an expected error has occurred: "
		          << e.what() << std::endl;
	}

	// a custom handler that you write yourself
	// is only called when an error happens with loading or
	// running the script
	auto result2 = lua.safe_script("123 bad.code",
	     [](lua_State*, sol::protected_function_result pfr) {
		     // pfr will contain things that went wrong, for
		     // either loading or executing the script the user
		     // can do whatever they like here, including
		     // throw. Otherwise...
		     sol::error err = pfr;
		     std::cout
		          << "An error (an expected one) occurred: "
		          << err.what() << std::endl;

		     // ... they need to return the
		     // protected_function_result
		     return pfr;
	     });

	std::cout << std::endl;

	return 0;
}