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.2k stars 516 forks source link

memory smashing with custom properties #1374

Open otristan opened 2 years ago

otristan commented 2 years ago

Hi,

The following code leads to some memory smashing from time to time. It seems related to the automatic wrapping of const std::vector

Using lua 5.2 on Xcode Version 12.2 (12B45b)

I wonder is this related to the same issue fixed in #1315

Thanks !

#define SOL_USING_CXX_LUA 1

#include "sol/sol.hpp"
#include <vector>

struct A
{
public:
  A() { }

  sol::object index(sol::object key)
  {
    if (mProperties.valid())
    {
      return mProperties[key];
    }
    return sol::object();
  }

  void new_index(sol::object key, sol::object value, sol::this_state L)
  {
    if (!mProperties.valid())
    {
      sol::state_view lua(L);
      mProperties = lua.create_table();
    }
    mProperties[key] = value;
  }

protected:
  sol::table mProperties;
};

int main(void)
{
  A a;
  sol::state lua;
  lua.open_libraries(sol::lib::base,
                     sol::lib::package,
                     sol::lib::table,
                     sol::lib::debug,
                     sol::lib::string,
                     sol::lib::math,
                     sol::lib::bit32,
                     sol::lib::coroutine
                     );

  lua.new_usertype<A>("A",
                      sol::meta_function::index, &A::index,
                      sol::meta_function::new_index, &A::new_index);

  lua.globals()["A"] = &a;

  const auto& code = R"(
  for i=1, 300 do
    co = coroutine.create( function()
      A.foo = 7
      A.bar = {}
      for i=1, 170 do
          A.bar[i] = i
      end
    end)
    coroutine.resume(co)
    print(A.foo)
    for _, value in pairs(A.bar) do
        print(value)
    end
  end

    )";

  // call lua code directly
  lua.script(code);

    return 0;
}