-
-
Notifications
You must be signed in to change notification settings - Fork 554
/
Copy pathstatic_variables.cpp
63 lines (49 loc) · 1.48 KB
/
static_variables.cpp
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
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct test {
static int muh_variable;
};
int test::muh_variable = 25;
int main() {
std::cout << "=== static_variables ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.new_usertype<test>("test",
"direct",
sol::var(2),
"global",
sol::var(test::muh_variable),
"ref_global",
sol::var(std::ref(test::muh_variable)));
int direct_value = lua["test"]["direct"];
// direct_value == 2
SOL_ASSERT(direct_value == 2);
std::cout << "direct_value: " << direct_value << std::endl;
int global = lua["test"]["global"];
int global2 = lua["test"]["ref_global"];
// global == 25
// global2 == 25
SOL_ASSERT(global == 25);
SOL_ASSERT(global2 == 25);
std::cout << "First round of values --" << std::endl;
std::cout << global << std::endl;
std::cout << global2 << std::endl;
test::muh_variable = 542;
global = lua["test"]["global"];
// global == 25
// global is its own memory: was passed by value
global2 = lua["test"]["ref_global"];
// global2 == 542
// global2 was passed through std::ref
// global2 holds a reference to muh_variable
// if muh_variable goes out of scope or is deleted
// problems could arise, so be careful!
SOL_ASSERT(global == 25);
SOL_ASSERT(global2 == 542);
std::cout << "Second round of values --" << std::endl;
std::cout << "global : " << global << std::endl;
std::cout << "global2: " << global2 << std::endl;
std::cout << std::endl;
return 0;
}