sol2 icon indicating copy to clipboard operation
sol2 copied to clipboard

Custom containers holding Lua tables

Open uramer opened this issue 2 years ago • 0 comments

Hello.

What's the recommended way to create custom containers, which can hold indirect self-references? From my testing, they never get garbage-collected.

Example Lua code

do
  local container = myApi.makeContainer()
  container:insert({
    callback = function()
      container:insert({}) -- capture container in a closure
    end
  })
end
collectGarbage()
-- container doesn't get garbage-collected because of the cyclic reference

The cases I tested were basically various std::vector / std::map wrappers, or even just a struct with a sol::table field, passed to Lua as userdata with usertypes.

Is such a pattern not supported at all, and all such containers should be implemented on the Lua side?

uramer avatar Jan 15 '23 16:01 uramer