@@ -125,9 +125,11 @@ namespace sol {
125125 template <typename T, bool checked, bool clean_stack>
126126 struct constructor_match {
127127 T* obj_;
128+ reference* obj_lua_ref_;
128129 stack::stack_detail::undefined_metatable* p_umf_;
129130
130- constructor_match (T* obj_ptr, stack::stack_detail::undefined_metatable& umf) : obj_(obj_ptr), p_umf_(&umf) {
131+ constructor_match (T* obj_ptr, reference& obj_lua_ref, stack::stack_detail::undefined_metatable& umf)
132+ : obj_(obj_ptr), obj_lua_ref_(&obj_lua_ref), p_umf_(&umf) {
131133 }
132134
133135 template <typename Fx, std::size_t I, typename ... R, typename ... Args>
@@ -137,7 +139,14 @@ namespace sol {
137139 // construct userdata table
138140 // SPECIFICALLY, after we've created it successfully.
139141 // If the constructor exits for any reason we have to break things down...
140- (*this ->p_umf_ )();
142+ if constexpr (clean_stack) {
143+ obj_lua_ref_->push ();
144+ (*this ->p_umf_ )();
145+ obj_lua_ref_->pop ();
146+ }
147+ else {
148+ (*this ->p_umf_ )();
149+ }
141150 return result;
142151 }
143152 };
@@ -326,7 +335,7 @@ namespace sol {
326335
327336 // put userdata at the first index
328337 lua_insert (L, 1 );
329- construct_match<T, TypeLists...>(constructor_match<T, checked, clean_stack>(obj, umf), L, argcount, 1 + static_cast <int >(syntax));
338+ construct_match<T, TypeLists...>(constructor_match<T, checked, clean_stack>(obj, userdataref, umf), L, argcount, 1 + static_cast <int >(syntax));
330339
331340 userdataref.push ();
332341 return 1 ;
@@ -654,7 +663,7 @@ namespace sol {
654663 argcount -= static_cast <int >(syntax);
655664
656665 T* obj = detail::usertype_allocate<T>(L);
657- stack_reference userdataref (L, -1 );
666+ reference userdataref (L, -1 );
658667 stack::stack_detail::undefined_metatable umf (L, &meta[0 ], &stack::stack_detail::set_undefined_methods_on<T>);
659668
660669 // put userdata at the first index
@@ -663,7 +672,8 @@ namespace sol {
663672 // we have to kill the data, but only if the cosntructor is successfulyl invoked...
664673 // if it's not successfully invoked and we panic,
665674 // we cannot actually deallcoate/delete the data.
666- construct_match<T, Args...>(constructor_match<T, checked, clean_stack>(obj, umf), L, argcount, boost + 1 + 1 + static_cast <int >(syntax));
675+ construct_match<T, Args...>(
676+ constructor_match<T, checked, clean_stack>(obj, userdataref, umf), L, argcount, boost + 1 + 1 + static_cast <int >(syntax));
667677
668678 userdataref.push ();
669679 return 1 ;
0 commit comments