| 19 | }; |
| 20 | |
| 21 | int main(int, char*[]) { |
| 22 | std::cout << "=== userdata ===" << std::endl; |
| 23 | |
| 24 | sol::state lua; |
| 25 | |
| 26 | Doge dog { 30 }; |
| 27 | |
| 28 | // fresh one put into Lua |
| 29 | lua["dog"] = Doge {}; |
| 30 | // Copy into lua: destroyed by Lua VM during garbage |
| 31 | // collection |
| 32 | lua["dog_copy"] = dog; |
| 33 | // OR: move semantics - will call move constructor if |
| 34 | // present instead Again, owned by Lua |
| 35 | lua["dog_move"] = std::move(dog); |
| 36 | lua["dog_unique_ptr"] = std::make_unique<Doge>(25); |
| 37 | lua["dog_shared_ptr"] = std::make_shared<Doge>(31); |
| 38 | |
| 39 | // Identical to above |
| 40 | Doge dog2 { 30 }; |
| 41 | lua.set("dog2", Doge {}); |
| 42 | lua.set("dog2_copy", dog2); |
| 43 | lua.set("dog2_move", std::move(dog2)); |
| 44 | lua.set("dog2_unique_ptr", |
| 45 | std::unique_ptr<Doge>(new Doge(25))); |
| 46 | lua.set("dog2_shared_ptr", |
| 47 | std::shared_ptr<Doge>(new Doge(31))); |
| 48 | |
| 49 | // Note all of them can be retrieved the same way: |
| 50 | Doge& lua_dog = lua["dog"]; |
| 51 | Doge& lua_dog_copy = lua["dog_copy"]; |
| 52 | Doge& lua_dog_move = lua["dog_move"]; |
| 53 | Doge& lua_dog_unique_ptr = lua["dog_unique_ptr"]; |
| 54 | Doge& lua_dog_shared_ptr = lua["dog_shared_ptr"]; |
| 55 | SOL_ASSERT(lua_dog.tailwag == 50); |
| 56 | SOL_ASSERT(lua_dog_copy.tailwag == 30); |
| 57 | SOL_ASSERT(lua_dog_move.tailwag == 30); |
| 58 | SOL_ASSERT(lua_dog_unique_ptr.tailwag == 25); |
| 59 | SOL_ASSERT(lua_dog_shared_ptr.tailwag == 31); |
| 60 | |
| 61 | // lua will treat these types as opaque, and you will be |
| 62 | // able to pass them around to C++ functions and Lua |
| 63 | // functions alike |
| 64 | |
| 65 | // Use a C++ reference to handle memory directly |
| 66 | // otherwise take by value, without '&' |
| 67 | lua["f"] = [](Doge& dog) { |
| 68 | std::cout << "dog wags its tail " << dog.tailwag |
| 69 | << " times!" << std::endl; |
| 70 | }; |
| 71 | |
| 72 | // if you bind a function using a pointer, |
| 73 | // you can handle when `nil` is passed |
| 74 | lua["handling_f"] = [](Doge* dog) { |
| 75 | if (dog == nullptr) { |
| 76 | std::cout << "dog was nil!" << std::endl; |
| 77 | return; |
| 78 | } |