lua-users home
lua-l archive

Re: garbage collection and setfenv

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


So my non-trimmed code posted previously is actually a simplified version of my real code, which I won't post here because it's too big. I'm still running into the problem where something is maintaining a reference to my environment table, but for the life of me I can't figure out where.

Is there a facility to trace back references for a given object? I didn't see something like that in the debug interface.

On Tue, Mar 18, 2008 at 7:51 PM, Matthew Armstrong <turkeypotpie@gmail.com> wrote:
With response to Daniel Stephens code:

----------------------------------------------------------------------------------

function detectGc()
print("!!! cleanup")
ldb();
end

function tryThis(gcFunc)
myVar = GfcTimer();
local mt = getmetatable(myVar);
mt.__gc = gcFunc;
end
----------------------------------------------------------------------------------

I break correctly if I define my garbage handler this way, or if I just pass it in through my environment table. So it looks like it was just my detection method that skewed my view of what was going on :)


With response to Patrick Donnelly's code:

----------------------------------------------------------------------------------

function tryThis()
myVar = newproxy()
print(myVar)
local mt = getmetatable(myVar) or {}
debug.setmetatable(myVar, mt);
mt.__gc = function()
print("!!! cleanup")
end
end

function yup()
setfenv(tryThis, setmetatable({}, { __index = _G }))
tryThis()
setfenv(tryThis, {})
collectgarbage()
end

yup();
----------------------------------------------------------------------------------

I don't break correctly, as he does, when I use the code verbatim (except for substituting newproxy for GfcTimer). I don't know what's causing the discrepancy between our two results.
Note: I did have a local variable 'env' referencing the environment, but I set it to nil. I'm not sure whether it would make a difference in either way.

Thanks everyone for your help :)


On Tue, Mar 18, 2008 at 7:24 PM, Patrick Donnelly <batrick.donnelly@gmail.com> wrote:
Running the following in the Lua interpretter:

function tryThis()
myVar = newproxy()
print(myVar)
local mt = getmetatable(myVar) or {}
debug.setmetatable(myVar, mt);
mt.__gc = function()
print("!!! cleanup")
end
end

function yup()
setfenv(tryThis, setmetatable({}, { __index = _G }))
tryThis()
setfenv(tryThis, {})
collectgarbage()
end

yup();

The following is output:
batrick@waterdeep:~$ lua test.lua
userdata: 0x806f9ec
!!! cleanup

I believe your problem is that you are expecting the environment to be
collected when a local variable has a reference to it =)

Cheers,

--
-Patrick Donnelly

"One of the lessons of history is that nothing is often a good thing
to do and always a clever thing to say."

-Will Durant



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