File: usertype_initializers.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-- 1,782 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 <memory>
#include <iostream>

struct holy {
private:
	holy() : data() {
	}
	holy(int value) : data(value) {
	}
	~holy() {
	}

public:
	struct deleter {
		void operator()(holy* p) const {
			destroy(*p);
		}
	};

	const int data;

	static std::unique_ptr<holy, deleter> create() {
		std::cout << "creating 'holy' unique_ptr directly and "
		             "letting sol/Lua handle it"
		          << std::endl;
		return std::unique_ptr<holy, deleter>(new holy(50));
	}

	static void initialize(holy& uninitialized_memory) {
		std::cout << "initializing 'holy' userdata at "
		          << static_cast<void*>(&uninitialized_memory)
		          << std::endl;
		// receive uninitialized memory from Lua:
		// properly set it by calling a constructor
		// on it
		// "placement new"
		new (&uninitialized_memory) holy();
	}

	static void destroy(holy& memory_from_lua) {
		std::cout << "destroying 'holy' userdata at "
		          << static_cast<void*>(&memory_from_lua)
		          << std::endl;
		memory_from_lua.~holy();
	}
};

int main() {
	std::cout << "=== usertype_initializers ===" << std::endl;
	{ // additional scope to make usertype destroy earlier
		sol::state lua;
		lua.open_libraries();

		lua.new_usertype<holy>("holy",
		     "new",
		     sol::initializers(&holy::initialize),
		     "create",
		     sol::factories(&holy::create),
		     sol::meta_function::garbage_collect,
		     sol::destructor(&holy::destroy),
		     "data",
		     &holy::data);

		lua.script(R"(
h1 = holy.create()
h2 = holy.new()
print('h1.data is ' .. h1.data)
print('h2.data is ' .. h2.data)
)");
		holy& h1 = lua["h1"];
		holy& h2 = lua["h2"];
		SOL_ASSERT(h1.data == 50);
		SOL_ASSERT(h2.data == 0);
	}
	std::cout << std::endl;
}