forked from ThePhD/sol2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusertype_initializers.cpp
More file actions
79 lines (69 loc) · 1.74 KB
/
usertype_initializers.cpp
File metadata and controls
79 lines (69 loc) · 1.74 KB
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_c_assert(h1.data == 50);
sol_c_assert(h2.data == 0);
}
std::cout << std::endl;
}