File: basic.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 (79 lines) | stat: -rw-r--r-- 2,191 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
76
77
78
79
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {
	std::cout << "=== basic ===" << std::endl;
	// create an empty lua state
	sol::state lua;

	// by default, libraries are not opened
	// you can open libraries by using open_libraries
	// the libraries reside in the sol::lib enum class
	lua.open_libraries(sol::lib::base);
	// you can open all libraries by passing no arguments
	// lua.open_libraries();

	// call lua code directly
	lua.script("print('hello world')");

	// call lua code, and check to make sure it has loaded and
	// run properly:
	auto handler = &sol::script_default_on_error;
	lua.script("print('hello again, world')", handler);

	// Use a custom error handler if you need it
	// This gets called when the result is bad
	auto simple_handler =
	     [](lua_State*, sol::protected_function_result result) {
		     // You can just pass it through to let the
		     // call-site handle it
		     return result;
	     };
	// the above lambda is identical to sol::simple_on_error,
	// but it's shown here to show you can write whatever you
	// like

	//
	{
		auto result = lua.script(
		     "print('hello hello again, world') \n return 24",
		     simple_handler);
		if (result.valid()) {
			std::cout << "the third script worked, and a "
			             "double-hello statement should "
			             "appear above this one!"
			          << std::endl;
			int value = result;
			SOL_ASSERT(value == 24);
		}
		else {
			std::cout << "the third script failed, check the "
			             "result type for more information!"
			          << std::endl;
		}
	}

	{
		auto result
		     = lua.script("does.not.exist", simple_handler);
		if (result.valid()) {
			std::cout << "the fourth script worked, which it "
			             "wasn't supposed to! Panic!"
			          << std::endl;
			int value = result;
			SOL_ASSERT(value == 24);
		}
		else {
			sol::error err = result;
			std::cout << "the fourth script failed, which "
			             "was intentional!\t\nError: "
			          << err.what() << std::endl;
		}
	}

	std::cout << std::endl;

	return 0;
}