lua-users home
lua-l archive

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


Am 21.06.19 um 00:16 schröbte Soni "They/Them" L.:

local function do_something_with_file(f)
     local <with> f = f -- f:__enter()
     f:write("hello!\n")
     -- f:__close()
end

You shouldn't dispose objects you didn't allocate in any Lua version because the code that did allocate the object might still need it after you have returned. And that makes <toclose>/<with> nesting superfluous.


do_something_with_file(io.open("foo", "w")) -- okay, file gets closed

local <with> f = io.open("bar", "w") -- f:__enter()
do_something_with_file(f) -- doesn't close file
f:write("goodbye!\n")
-- f:__close() -- file gets closed

I was thinking about this:

local f = io.open("bar", "w")
do_something_with_file(f) -- closes file
f:write("goodbye!\n") -- error


Philipp