Luabridge weak reference to LuaRef data
Asked Answered
C

1

7

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?

Cortneycorty answered 27/5, 2013 at 16:49 Comment(0)
C
1

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)
    
Cortneycorty answered 30/5, 2013 at 15:51 Comment(1)
if you accept your own answer, you will get less people to look at your question. You can still accept it afterwards.Hirundine

© 2022 - 2024 — McMap. All rights reserved.