1 #define SOL_ALL_SAFETIES_ON 1 2 #include <sol/sol.hpp> 3 4 #include <iostream> 5 6 struct ree { 7 int value = 1; reeree8 ree() { 9 } reeree10 ree(int v) : value(v) { 11 } 12 }; 13 main()14int main() { 15 16 std::cout << "=== special pointers -- modify in place ===" << std::endl; 17 18 sol::state lua; 19 20 auto new_shared_ptr = [](sol::stack_reference obj) { 21 // works just fine 22 sol::stack::modify_unique_usertype(obj, [](std::shared_ptr<ree>& sptr) { sptr = std::make_shared<ree>(sptr->value + 1); }); 23 }; 24 25 auto reset_shared_ptr = [](sol::stack_reference obj) { 26 sol::stack::modify_unique_usertype(obj, [](std::shared_ptr<ree>& sptr) { 27 // THIS IS SUCH A BAD IDEA AAAGH 28 sptr.reset(); 29 // DO NOT reset to nullptr: 30 // change it to an actual NEW value... 31 // otherwise you will inject a nullptr into the userdata representation... 32 // which will NOT compare == to Lua's nil 33 }); 34 }; 35 36 lua.set_function("f", new_shared_ptr); 37 lua.set_function("f2", reset_shared_ptr); 38 lua.set_function("g", [](ree* r) { std::cout << r->value << std::endl; }); 39 40 lua["p"] = std::make_shared<ree>(); 41 lua.script("g(p) -- okay"); 42 lua.script("f(p)"); 43 lua.script("g(p) -- okay"); 44 // uncomment the below for 45 // segfault/read-access violation 46 lua.script("f2(p)"); 47 // lua.script("g(p) -- kaboom"); 48 49 return 0; 50 } 51