From cd092d3bfb8465835526e1f171d9432f8992172b Mon Sep 17 00:00:00 2001 From: Rapptz Date: Sun, 27 Apr 2014 05:09:28 -0400 Subject: [PATCH] Add new_userdata to create internally memory managed userdata from sol::state --- sol/state.hpp | 11 +++++++++++ tests.cpp | 27 ++++++++++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/sol/state.hpp b/sol/state.hpp index 5453c5c2..3f47322c 100644 --- a/sol/state.hpp +++ b/sol/state.hpp @@ -56,6 +56,7 @@ enum class lib : char { class state { private: + std::vector> classes; std::unique_ptr L; table reg; table global; @@ -156,6 +157,16 @@ public: return *this; } + template + state& new_userdata(const std::string& name, Args&&... args) { + constructors> ctor; + classes.emplace_back(std::make_shared>(name, ctor, std::forward(args)...)); + auto&& ptr = classes.back(); + auto udata = std::static_pointer_cast>(ptr); + global.set_userdata(*udata); + return *this; + } + template table create_table(T&& key, int narr = 0, int nrec = 0) { lua_createtable(L.get(), narr, nrec); diff --git a/tests.cpp b/tests.cpp index d4792538..0c76980c 100644 --- a/tests.cpp +++ b/tests.cpp @@ -422,4 +422,29 @@ TEST_CASE("tables/userdata constructors", "Show that we can create classes from sol::object z = lua.get("z"); REQUIRE((y.as() == 7)); REQUIRE((z.as() == 9)); -} \ No newline at end of file +} + +TEST_CASE("tables/userdata utility", "Show internal management of classes registered through new_userdata") { + sol::state lua; + + lua.new_userdata("fuser", "add", &fuser::add, "add2", &fuser::add2); + + lua.script("a = fuser.new()\n" + "b = a:add(1)\n" + "c = a:add2(1)\n"); + + sol::object a = lua.get("a"); + sol::object b = lua.get("b"); + sol::object c = lua.get("c"); + REQUIRE((a.is())); + auto atype = a.get_type(); + auto btype = b.get_type(); + auto ctype = c.get_type(); + REQUIRE((atype == sol::type::userdata)); + REQUIRE((btype == sol::type::number)); + REQUIRE((ctype == sol::type::number)); + int bresult = b.as(); + int cresult = c.as(); + REQUIRE(bresult == 1); + REQUIRE(cresult == 3); +}