Luabridge weak link to LuaRef data

Consider the following example:

function Process() local Container=NewContainer() Container:On(EventType.Add,function() Container:DoSomething() end) -- Does not Garbage Collect end 

In luabridge, I save function() as a LuaRef , which extends the lifetime of the Container , and it will not be GCed because it is RefCountedObjectPtr

Here is a workaround that I use to use a weak table that works but looks ugly:

 function Process() local Container=NewContainer() local ParamsTable={ Container=Container } setmetatable(ParamsTable, { __mode = 'k' }) Container:On(EventType.Add,function() ParamsTable.Container:DoSomething() end) -- Garbage Collects fine end 

Is there a way to have a LuaRef function that works similarly to this? Or maybe there is another workaround?

+7
source share
1 answer

This is how I approached this problem:

  • Create a wrapper class in a C ++ class class luabridge (if you have class Display.A() in C ++, create class A() in Lua)
  • Keep a weak table inside this wrapper class ( self.WeakTable={} and setmetatable(self.WeakTable, { __mode = 'k' }) )
  • In a weak table, the link is self: ( self.WeakTable.self=self )
  • Pass self.WeakTable to C ++ and save as LuaRef - this will be gc
  • Create a wrapper like this:

     Container:On(EventType.Add,function(WeakTableParams) WeakTableParams.self.Callback(); end) 
+1
source

All Articles