lua-users home
lua-l archive

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


On Sat, May 23, 2020 at 1:59 PM Andrea <andrea.l.vitali@gmail.com> wrote:
>
> What happens in the following case:
> - I mark a local as to-be-closed,
> - then this is used as upvalue for an enclosed function,
> - then the function returns the enclosed function
> - a closure is created: the upvalue is moved from the stack to the heap
> - ...and here is where I do not know what happens: is the local/upvalue out of scope now?
> - ...does _close() get executed or not?

It's easy to test this and see what happens:

    local function onclose(t)
     t.closed = true
     print 'in onclose'
    end

    local function f()
     local x <close> = setmetatable({closed = false}, {__close = onclose})
     local function g()
       return x
     end
     return g
    end

    local g = f()
    print 'between f and g'
    local x = g()
    print(x.closed)

When I run that, I get "in onclose", "between f and g", and then
"true". And this is unrelated to the "g" closure. If "f" instead
directly returned "x", it still gets closed before the caller sees it.

Joseph C. Sible