lua-users home
lua-l archive

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


Can this code solve auto close problem https://pastebin.com/LPxHKKp8

-- helper function

function scope(self)
    local result
    self=self or {}
    self.list={}
    self.error=self.error or error
    local function auto(arg,close,msg)
        if arg then
            table.insert(self.list,{ arg=arg, fn=close or io.close })
        else
            self.error(msg or "init error",2)
        end
        return arg
    end
    if self.init then self.init(auto) end
    local ok,err=pcall(function() result=table.pack(self.body()) end)
    if self.done then self.done(ok,err) end
    for _,close in pairs(self.list) do close.fn(close.arg) end
    if not ok then self.error(err) end
    return table.unpack(result)
end

-- usage:

function test()
    local src,dst
    scope {
        init=function(auto)
            src=auto(io.open("file1.txt","w"))
            dst=auto(io.open("file2.txt","w"),function(f) print "close
file" f:close() end )
        end,
        body=function()
            src:write "hello"
            dst:write "world"
        end,
    }
end

test()

вт, 25 июн. 2019 г. в 20:31, Francisco Olarte <folarte@peoplecall.com>:
>
> Sergey:
>
> On Tue, Jun 25, 2019 at 6:25 PM Sergey Kovalev <kovserg33@gmail.com> wrote:
> > __unreference should call immediately when reference count to zero,
> > unliket __gc it is called latter then there is no way to stand more or
> > when explicitly call collectgarbage()
>
> Lua does not work by reference count.
>
> OTOH, <toclose> is really handy to implement your own ref-count
> schemes, I'm planning to use it for that if I ever switchto 5.4.
>
> Francisco Olarte.
>