forked from ThePhD/sol2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer_usertype_as_container.cpp
More file actions
89 lines (73 loc) · 1.85 KB
/
container_usertype_as_container.cpp
File metadata and controls
89 lines (73 loc) · 1.85 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
80
81
82
83
84
85
86
87
88
89
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <vector>
#include <numeric>
#include <iostream>
class number_storage {
private:
std::vector<int> data;
public:
number_storage(int i) {
data.push_back(i);
}
int accumulate() const {
return std::accumulate(data.begin(), data.end(), 0);
}
public:
using value_type = decltype(data)::value_type;
using iterator = decltype(data)::iterator;
using size_type = decltype(data)::size_type;
iterator begin() {
return iterator(data.begin());
}
iterator end() {
return iterator(data.end());
}
size_type size() const noexcept {
return data.size();
}
size_type max_size() const noexcept {
return data.max_size();
}
void push_back(int value) {
data.push_back(value);
}
bool empty() const noexcept {
return data.empty();
}
};
namespace sol {
template <>
struct is_container<number_storage> : std::false_type { };
} // namespace sol
int main(int, char*[]) {
std::cout << "=== container as container ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<number_storage>("number_storage",
sol::constructors<number_storage(int)>(),
"accumulate",
&number_storage::accumulate,
"iterable",
[](number_storage& ns) {
return sol::as_container(
ns); // treat like a container, despite
// is_container specialization
});
lua.script(R"(
ns = number_storage.new(23)
print("accumulate before:", ns:accumulate())
-- reference original usertype like a container
ns_container = ns:iterable()
ns_container:add(24)
ns_container:add(25)
-- now print to show effect
print("accumulate after :", ns:accumulate())
)");
number_storage& ns = lua["ns"];
number_storage& ns_container = lua["ns_container"];
sol_c_assert(&ns == &ns_container);
sol_c_assert(ns.size() == 3);
std::cout << std::endl;
return 0;
}