1

So I am exposing complicated data objects that are both created entirely within a C++ environment but more recently I have made it so Lua can also create an instances of these objects. I use the UserData to track where the allocation happened so when __gc is called it knows what it is supposed to do.

Is Lua smart enough to know a reference to a user data it created is stored in a user data block that it did not create?

Code Sample

function AddNewSubjObject(containerId, subObjectType)
  local containerObject = meta_ContainerObject:getContainer(containerId)
  local newSubObject    = meta_SubObject:CreateNew(subObjectType)

  containerObject.AddChild(newSubObject)
  return containerObject;
end

We get a local variable to the userdata object that can contain other objects. We then create a new object that its only tracking is in Lua. Finally we call a method that will store the sub object in the container object.

When this function returns, to me it looks like it has removed all references to the newSubObject so I fear it will delete the memory allocated for it even though it is still being referenced..

Will this either leak memory by not cleaning up the objects properly or will it corrupt memory by deleting it when it is still be potentially used? Basically I am wondering if this is a situation that has to be considered and handled when exposing userdata via Lua.

James
  • 1,651
  • 2
  • 18
  • 24
  • I don't see a question here. Just an incomplete experiment you've yet to test. If you find any problems, then come back. – warspyking Jan 07 '16 at 01:26

1 Answers1

2

The Lua garbage collector does not look inside userdata.

Lua provides weak tables to manage these kinds of references. See PiL Chapter 17. You can use a table with weak keys of subObjects and values of the container of the subObject. When the container is collected so will the subObjects.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
  • Are weak tables possible via the C API? I would rather be able to find a way to do this (and while I would enjoy looking into this myself I simply do not have time) with out having to create a Lua based library wrapped around the metatable API I am creating to access the C data. – James Jan 07 '16 at 02:26
  • Sure, you can create and update weak tables from C; they're just tables with a simple metatable. An example is in this SO question: http://stackoverflow.com/questions/24087890/weak-table-and-gc-finalizer-using-c-api – Doug Currie Jan 07 '16 at 02:47