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

#include <iostream>

// Uses some of the fancier bits of sol2, including the
// "transparent argument", sol::this_state, which gets the
// current state and does not increment function arguments
sol::object fancy_func(
     sol::object a, sol::object b, sol::this_state s) {
	sol::state_view lua(s);
	if (a.is<int>() && b.is<int>()) {
		return sol::object(
		     lua, sol::in_place, a.as<int>() + b.as<int>());
	}
	else if (a.is<bool>()) {
		bool do_triple = a.as<bool>();
		return sol::object(lua,
		     sol::in_place_type<double>,
		     b.as<double>() * (do_triple ? 3 : 1));
	}
	// Can also use make_object
	return sol::make_object(lua, sol::lua_nil);
}

int main() {
	sol::state lua;

	lua["f"] = fancy_func;

	int result = lua["f"](1, 2);
	// result == 3
	SOL_ASSERT(result == 3);
	double result2 = lua["f"](false, 2.5);
	// result2 == 2.5
	SOL_ASSERT(result2 == 2.5);

	// call in Lua, get result
	// notice we only need 2 arguments here, not 3
	// (sol::this_state is transparent)
	lua.script("result3 = f(true, 5.5)");
	double result3 = lua["result3"];
	// result3 == 16.5
	SOL_ASSERT(result3 == 16.5);

	std::cout << "=== any_return ===" << std::endl;
	std::cout << "result : " << result << std::endl;
	std::cout << "result2: " << result2 << std::endl;
	std::cout << "result3: " << result3 << std::endl;
	std::cout << std::endl;

	return 0;
}