On Tue, Jul 21, 2020 at 5:52 PM Andrew Gierth wrote:
function f1(fn)
local fc <close>, f, err, errno = auto_close(io.open(fn,"r"))
--[[ check for errors ]]
--[[ do stuff with f, that might throw an error ]]
-- if successful, return the file to the caller
return fc:release()
end
function f2()
local fc <close>, f = auto_close(f1("filename"))
--[[ do stuff ]]
end
This does leave a small window for error in the auto_close call itself
Unfortunately, the window is a bit larger.
function f1(fn)
local obj <close> = create_temporary_obj()
local fc <close>, f, err, errno = auto_close(io.open(fn,"r"))
--[[ check for errors ]]
--[[ do stuff with f, that might throw an error ]]
-- if successful, return the file to the caller
return fc:release()
end
If an error is raised inside the "__close" metamethod of "obj", the file "f" remains non-closed.
When "obj" is being closed, the "fc:release()" is already complete and "f" is currently not protected.