lua-users home
lua-l archive

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


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> 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