File: indirect_function_calls.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 (77 lines) | stat: -rw-r--r-- 1,685 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
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

sol::variadic_results call_it(sol::object function_name,
     sol::variadic_args args, sol::this_environment env,
     sol::this_state L) {
	sol::state_view lua = L;
	// default to global table as environment
	sol::environment function_environment = lua.globals();
	if (env) {
		// if we have an environment, use that instead
		function_environment = env;
	}

	// get and call the function
	sol::protected_function pf
	     = function_environment[function_name];
	sol::protected_function_result res = pf(args);

	//
	sol::variadic_results results;
	if (!res.valid()) {
		// something went wrong: log/crash/whatever
		return results;
	}
	int returncount = res.return_count();
	for (int i = 0; i < returncount; i++) {
		// pass offset to get the object that was returned
		sol::object obj = res.get<sol::object>(i);
		results.push_back(obj);
	}
	// return the results
	return results;
}

int main(int, char*[]) {
	std::cout << "=== indirect function calls ===" << std::endl;

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

	lua["call_it"] = call_it;

	// some functions to call
	lua.script(R"(
function add (a, b)
	return a + b;
end

function subtract (a, b)
	return a - b;
end

function log (x)
	print(x)
end
)");

	// call the functions indirectly, using a name
	lua.script(R"(
		call_it("log", "hiyo")
		call_it("log", 24)
		subtract_result = call_it("subtract", 5, 1)
		add_result = call_it("add", 5, 1)
	)");

	int subtract_result = lua["subtract_result"];
	int add_result = lua["add_result"];

	SOL_ASSERT(add_result == 6);
	SOL_ASSERT(subtract_result == 4);

	std::cout << std::endl;
	return 0;
}