lua-users home
lua-l archive

Re: garbage collection and setfenv

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


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 によって変換されたページ (->オリジナル) /