1 #include <sol.hpp> 2 3 #include <iostream> 4 #include <cassert> 5 6 struct test { 7 static int muh_variable; 8 }; 9 int test::muh_variable = 25; 10 11 main()12int main() { 13 std::cout << "=== static_variables example ===" << std::endl; 14 15 sol::state lua; 16 lua.open_libraries(); 17 lua.new_usertype<test>("test", 18 "direct", sol::var(2), 19 "global", sol::var(test::muh_variable), 20 "ref_global", sol::var(std::ref(test::muh_variable)) 21 ); 22 23 int direct_value = lua["test"]["direct"]; 24 // direct_value == 2 25 assert(direct_value == 2); 26 std::cout << "direct_value: " << direct_value << std::endl; 27 28 int global = lua["test"]["global"]; 29 int global2 = lua["test"]["ref_global"]; 30 // global == 25 31 // global2 == 25 32 assert(global == 25); 33 assert(global2 == 25); 34 35 std::cout << "First round of values --" << std::endl; 36 std::cout << global << std::endl; 37 std::cout << global2 << std::endl; 38 39 test::muh_variable = 542; 40 41 global = lua["test"]["global"]; 42 // global == 25 43 // global is its own memory: was passed by value 44 45 global2 = lua["test"]["ref_global"]; 46 // global2 == 542 47 // global2 was passed through std::ref 48 // global2 holds a reference to muh_variable 49 // if muh_variable goes out of scope or is deleted 50 // problems could arise, so be careful! 51 52 assert(global == 25); 53 assert(global2 == 542); 54 55 std::cout << "Second round of values --" << std::endl; 56 std::cout << "global : " << global << std::endl; 57 std::cout << "global2: " << global2 << std::endl; 58 std::cout << std::endl; 59 60 return 0; 61 } 62