1 #define SOL_ALL_SAFETIES_ON 1
2 #include <sol/sol.hpp>
3 
4 #include <iostream>
5 #include <string>
6 
7 struct int_entry {
8 	int value;
9 
int_entryint_entry10 	int_entry() : value(0) {
11 	}
12 
int_entryint_entry13 	int_entry(int v) : value(v) {
14 	}
15 
to_stringint_entry16 	std::string to_string() const {
17 		return "int_entry(" + std::to_string(value) + ")";
18 	}
19 
operator ==int_entry20 	bool operator==(const int_entry& e) const {
21 		return value == e.value;
22 	}
23 };
24 
main(int,char * [])25 int main(int, char*[]) {
26 
27 	std::cout << "=== sol::lua_value/sol::array_value ===" << std::endl;
28 
29 	sol::state lua;
30 	lua.open_libraries(sol::lib::base, sol::lib::io);
31 
32 	sol::lua_value lv_int(lua, 56);
33 	sol::lua_value lv_int_table(lua, { 1, 2, 3, 4, 5 });
34 	sol::lua_value lv_map(lua, { { "bark bark", "meow hiss!" }, { 3, 4 }, { ":D", 6 } });
35 	sol::lua_value lv_mixed_table(lua, sol::array_value { 1, int_entry(2), 3, int_entry(4), 5 });
36 	sol::lua_value lv_mixed_nested_table(lua, sol::array_value { 1, int_entry(2), 3, int_entry(4), sol::array_value { 5, 6, int_entry(7), "8" } });
37 
38 	const auto& code = R"(
39 		function real_print_recursive (e, level)
40 			local et = type(e)
41 			if et == 'table' then
42 				io.write("{ ")
43 				local iters = 0
44 				for k, v in pairs(e) do
45 					if iters ~= 0  then
46 						io.write(", ")
47 					end
48 					real_print_recursive(k, level + 1)
49 					io.write(": ")
50 					real_print_recursive(v, level + 1)
51 					iters = iters + 1
52 				end
53 				io.write(" }")
54 			elseif et == 'string' then
55 				io.write('"')
56 				io.write(e)
57 				io.write('"')
58 			else
59 				io.write(tostring(e))
60 			end
61 			if level == 0 then
62 				io.write("\n")
63 			end
64 		end
65 
66 		function print_recursive (e)
67 			real_print_recursive(e, 0)
68 		end
69 	)";
70 
71 	sol::optional<sol::error> maybe_error = lua.safe_script(code, sol::script_pass_on_error);
72 	if (maybe_error) {
73 		std::cerr << maybe_error->what() << std::endl;
74 		return 1;
75 	}
76 	sol::function print_recursive = lua["print_recursive"];
77 
78 	// show it printed out
79 	std::cout << "lv_int: " << std::endl;
80 	print_recursive(lv_int);
81 	std::cout << std::endl;
82 
83 	std::cout << "lv_int_table: " << std::endl;
84 	print_recursive(lv_int_table);
85 	std::cout << std::endl;
86 
87 	std::cout << "lv_map: " << std::endl;
88 	print_recursive(lv_map);
89 	std::cout << std::endl;
90 
91 	std::cout << "lv_mixed_table: " << std::endl;
92 	print_recursive(lv_mixed_table);
93 	std::cout << std::endl;
94 
95 	std::cout << "lv_mixed_nested_table: " << std::endl;
96 	print_recursive(lv_mixed_nested_table);
97 	std::cout << std::endl;
98 
99 	std::cout << std::endl;
100 
101 	return 0;
102 }