lua-users home
lua-l archive

Re: [ANN] Lua 5.4.0 (alpha) now available

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


Am 21.06.19 um 01:33 schröbte Soni "They/Them" L.:
On 2019年06月20日 8:28 p.m., Philipp Janda wrote:
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
my point is <toclose> could be an option to support nested contexts. in addition to plain old :close() that only does unnested contexts. it would be useful because you'd have two ways to use the same function. it improves code reuse and thus improves readability and maintainability!
Quoted above are _three_ ways to use the same function. With `do_something_with_file()` potentially closing its argument only two of those ways work.
Philipp

AltStyle によって変換されたページ (->オリジナル) /