lua-users home
lua-l archive

[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