Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Luabridge weak reference 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 store the function() as LuaRef which extends the lifetime for the Container and it will not be GCed because it's a RefCountedObjectPtr

Here is a workaround that I use to use a weak table which works, but it 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 any way to have a LuaRef that functions similar to this? Or maybe there is another workaround?

like image 670
Grapes Avatar asked May 27 '13 16:05

Grapes


1 Answers

Here is the way I approached this problem:

  1. Create a wrapper class around C++ luabridge class (If you have class Display.A() in C++, create class A() in Lua)
  2. Store a weak table inside that wrapper class (self.WeakTable={} and setmetatable(self.WeakTable, { __mode = 'k' }))
  3. In the weak table, reference self: (self.WeakTable.self=self)
  4. Pass self.WeakTable to C++ and store in as LuaRef - this will gc
  5. Create a wrapper function like so:

    Container:On(EventType.Add,function(WeakTableParams) 
       WeakTableParams.self.Callback();
    end)
    
like image 139
Grapes Avatar answered Oct 11 '22 20:10

Grapes