File: running_lua_code_safely.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 (75 lines) | stat: -rw-r--r-- 2,163 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <fstream>
#include <iostream>

int main(int, char*[]) {
	std::cout << "=== running lua code (safely) ==="
	          << std::endl;

	{
		std::ofstream out("a_lua_script.lua");
		out << "print('hi from a lua script file')";
	}

	sol::state lua;
	lua.open_libraries(sol::lib::base);

	// load and execute from string
	auto result = lua.safe_script(
	     "a = 'test'", sol::script_pass_on_error);
	if (!result.valid()) {
		sol::error err = result;
		std::cerr << "The code has failed to run!\n"
		          << err.what() << "\nPanicking and exiting..."
		          << std::endl;
		return 1;
	}

	// load and execute from file
	auto script_from_file_result = lua.safe_script_file(
	     "a_lua_script.lua", sol::script_pass_on_error);
	if (!script_from_file_result.valid()) {
		sol::error err = script_from_file_result;
		std::cerr
		     << "The code from the file has failed to run!\n"
		     << err.what() << "\nPanicking and exiting..."
		     << std::endl;
		return 1;
	}

	// run a script, get the result
	sol::optional<int> maybe_value = lua.safe_script(
	     "return 54", sol::script_pass_on_error);
	SOL_ASSERT(maybe_value.has_value());
	SOL_ASSERT(*maybe_value == 54);

	auto bad_code_result = lua.safe_script(
	     "123 herp.derp", sol::script_pass_on_error);
	SOL_ASSERT(!bad_code_result.valid());

	// you can also specify a handler function, and it'll
	// properly work here
	auto bad_code_result2 = lua.script("123 herp.derp",
	     [](lua_State*, sol::protected_function_result pfr) {
		     // pfr will contain things that went wrong, for
		     // either loading or executing the script Can
		     // throw your own custom error You can also just
		     // return it, and let the call-site handle the
		     // error if necessary.
		     return pfr;
	     });
	// it did not work
	SOL_ASSERT(!bad_code_result2.valid());

	// the default handler panics or throws, depending on your
	// settings uncomment for explosions: auto bad_code_result_2
	// = lua.script("bad.code", &sol::script_default_on_error);

	std::cout << std::endl;

	{ std::remove("a_lua_script.lua"); }

	return 0;
}