mirror of
https://github.com/ThePhD/sol2.git
synced 2024-03-22 13:10:44 +08:00
Add new_userdata to create internally memory managed userdata from sol::state
This commit is contained in:
parent
0ff295f61e
commit
cd092d3bfb
|
@ -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);
|
||||
|
|
27
tests.cpp
27
tests.cpp
|
@ -422,4 +422,29 @@ TEST_CASE("tables/userdata constructors", "Show that we can create classes from
|
|||
sol::object z = lua.get<sol::object>("z");
|
||||
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);
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user