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

#include <cmath>

struct vec {
	double x;
	double y;

	vec() : x(0), y(0) {
	}
	vec(double x, double y) : x(x), y(y) {
	}

	vec operator-(const vec& right) const {
		return vec(x - right.x, y - right.y);
	}
};

double dot(const vec& left, const vec& right) {
	return left.x * right.x + left.y * right.y;
}

vec operator+(const vec& left, const vec& right) {
	return vec(left.x + right.x, left.y + right.y);
}

int main() {
	sol::state lua;
	lua.open_libraries();

	lua.new_usertype<vec>(
	     "vec",
	     sol::constructors<vec(), vec(double, double)>(),
	     "dot",
	     &dot,
	     "norm",
	     [](const vec& self) {
		     double len = std::sqrt(dot(self, self));
		     return vec(self.x / len, self.y / len);
	     },
	     // we use `sol::resolve` because other operator+ can
	     // exist in the (global) namespace
	     sol::meta_function::addition,
	     sol::resolve<vec(const vec&, const vec&)>(::operator+),
	     sol::meta_function::subtraction,
	     &vec::operator-);

	lua.script(R"(
		v1 = vec.new(1, 0)
		v2 = vec.new(0, 1)
		-- as "member function"
		d1 = v1:dot(v2)
		-- as "static" / "free function"
		d2 = vec.dot(v1, v2)
		assert(d1 == d2)

		-- doesn't matter if
		-- bound as free function
		-- or member function:
		a1 = v1 + v2
		s1 = v1 - v2
)");

	vec& a1 = lua["a1"];
	vec& s1 = lua["s1"];

	SOL_ASSERT(a1.x == 1 && a1.y == 1);
	SOL_ASSERT(s1.x == 1 && s1.y == -1);

	lua["a2"] = lua["a1"];

	lua.script(R"(
		assert(a1 == a2)
	)");

	return 0;
}