ThePhD / sol2

Sol3 (sol2 v3.0) - a C++ <-> Lua API wrapper with advanced features and top notch performance - is here, and it's great! Documentation:
http://sol2.rtfd.io/
MIT License
4.16k stars 504 forks source link

new_usertype,program crash #1384

Open xncc123 opened 2 years ago

xncc123 commented 2 years ago

Sorry, my english is very bad。When I create an object of user-defined type in lua script。It throws an error when no corresponding constructor is found。But,it still create a lua object of user data type。then when lua gc run,it will call the destructor of user-defined type,then the program crash。

#include <sol/sol.hpp>
#include <iostream>

class Foo
{
public:
    Foo(int id, const char* name)
        : id_(id), name_(name) {}
    ~Foo() { 
            std::cout << __FUNCTION__ << ",id=" << id_ << ",name=" << name_ << std::endl;
    }
    void Print() { 
            std::cout << __FUNCTION__ << ",id=" << id_ << ",name=" << name_ << std::endl;
    }
private:
    int id_;
    std::string name_;
};

  static void Test()
  {
      sol::state lua;
      lua.open_libraries();

      lua.new_usertype<Foo>("Foo", sol::constructors<Foo(int, const char*)>(), "Print", &Foo::Print);

      auto res = lua.safe_script(
          //"foo1=Foo.new(123, 'abc') foo1:Print() "
          //"foo2=Foo.new() "
          "pcall(function() foo2=Foo.new() end) collectgarbage('collect') "
          , sol::script_pass_on_error);
      if (!res.valid()) {
          std::cout << "lua error:" << sol::stack::get<std::string>(lua, -1) << std::endl;
      }
  }

int main()
{
    Test();
    return 0;
}