lua-users home
lua-l archive

Re: garbage collection and setfenv

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


For the sake of the example, try defining your GC function outside and pass it in
function detectGc()
 print("!!! cleanup")
 ldb();
end
function tryThis(gcFunc)
 myVar = GfcTimer();
 local mt = getmetatable(myVar);
 mt.__gc = gcFunc;
end
then use tryThis(detectGc) instead of just tryThis()
Daniel.
Matthew Armstrong wrote:
I'm only using the __gc method for cleanup detection. If it is creating another reference to the environment, is there another way to detect collection that doesn't maintain a reference? On Tue, Mar 18, 2008 at 7:02 PM, Daniel Stephens <daniel@danielstephens.com <mailto:daniel@danielstephens.com>> wrote:
 The __gc closure you create inside tryThis will have inherited the
 global environment from tryThis at the time it was executed, so it's
 going to have a reference to that environment, but I'm not sure that
 would be a reachable reference.
 Daniel.
 Matthew Armstrong wrote:
 > I had already tried the setfenv(tryThis, {}) idea, and it didn't
 > work. After your mail, I also tried tryThis = nil, which also
 didn't
 > work. Here is my non-trimmed code:
 >
 > function tryThis()
 > myVar = GfcTimer()
 > local mt = getmetatable(myVar)
 > mt.__gc = function()
 > print("!!! cleanup")
 > ldb()
 > end
 >
 > --myVar = nil
 > end
 >
 > function yup()
 > local env = {}
 > setmetatable(env, { __index = _G })
 > setfenv(tryThis, env)
 >
 > tryThis()
 >
 > setfenv(tryThis, {})
 > tryThis = nil
 > env = nil
 >
 > collectgarbage()
 > end
 >
 > yup()
 >
 > Note: there is one external function, GfcTimer, which generates a
 > userdata object from our library.
 >
 > If I uncomment the line:
 >
 > -- myVar = nil
 >
 > ... then I get a confirmed call to the __gc method.
 >
 > Can you see anything else which would maintain a reference?
 >
 > On Tue, Mar 18, 2008 at 5:55 PM, Roberto Ierusalimschy
 > <roberto@inf.puc-rio.br <mailto:roberto@inf.puc-rio.br>
 <mailto:roberto@inf.puc-rio.br <mailto:roberto@inf.puc-rio.br>>>
 wrote:
 >
 > > So let's say I say:
 > >
 > > function tryThis()
 > > myVar = { foo="baz" }
 > > end
 > >
 > > local env = {}
 > > setfenv(tryThis, env)
 > > tryThis()
 > >
 > > My question is: when does myVar get collected? With my
 current
 > testing, it
 > > seems that myVar never gets collected. If so, how do I
 > "convince" it to be
 > > collected?
 >
 > 'env' is the environment of 'tryThis' (which is global), so it
 > cannot be
 > collected until tryThis is garbage or until you change its
 environment
 > again. You may try "tryThis = nil" or "setfenv(tryThis, {})".
 >
 > -- Roberto
 >
 >

AltStyle によって変換されたページ (->オリジナル) /