Add new_userdata to create internally memory managed userdata from sol::state

This commit is contained in:
Rapptz 2014-04-27 05:09:28 -04:00
parent 0ff295f61e
commit cd092d3bfb
2 changed files with 37 additions and 1 deletions

View File

@ -56,6 +56,7 @@ enum class lib : char {
class state {
private:
std::vector<std::shared_ptr<void>> classes;
std::unique_ptr<lua_State, void(*)(lua_State*)> L;
table reg;
table global;
@ -156,6 +157,16 @@ public:
return *this;
}
template<typename Class, typename... CTor, typename... Args>
state& new_userdata(const std::string& name, Args&&... args) {
constructors<types<CTor...>> ctor;
classes.emplace_back(std::make_shared<userdata<Class>>(name, ctor, std::forward<Args>(args)...));
auto&& ptr = classes.back();
auto udata = std::static_pointer_cast<userdata<Class>>(ptr);
global.set_userdata(*udata);
return *this;
}
template<typename T>
table create_table(T&& key, int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec);

View File

@ -423,3 +423,28 @@ TEST_CASE("tables/userdata constructors", "Show that we can create classes from
REQUIRE((y.as<int>() == 7));
REQUIRE((z.as<int>() == 9));
}
TEST_CASE("tables/userdata utility", "Show internal management of classes registered through new_userdata") {
sol::state lua;
lua.new_userdata<fuser>("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<sol::object>("a");
sol::object b = lua.get<sol::object>("b");
sol::object c = lua.get<sol::object>("c");
REQUIRE((a.is<sol::userdata_t>()));
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>();
int cresult = c.as<int>();
REQUIRE(bresult == 1);
REQUIRE(cresult == 3);
}