lua-users home
lua-l archive

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


It was thus said that the Great Egor Skriptunoff once stated:
> On Wed, Jul 3, 2019 at 9:19 AM Sean Conner <sean@conman.org> wrote:
> 
> > > Besides, it would be useful to have non-constant to-be-closed variables
> >
> >   So, what exactly should happen in this code?
> >
> >         local <toclose> f = io.open("a")
> >         local x = f
> >         f = io.open("b") -- should 'a' be closed?  or not because of x
> >         f = io.open("c") -- should 'b' be closed?
> >
> >
> >
> In your example only the last value in variable f would be evicted.

  Is that because of 'x'?  Or because that's the end of the scope?

> Simple example how non-constant to-be-closed variable might be useful:
> when you need to reopen a file during file operations (close the file, open
> it again with another access mode, save new file value into the
> to-be-closed variable)
> It is not known in compile-time would you need to re-open file or not.
> This situation requires to-be-closed variable to be writable.
> 
> do
>    local <toclose> f = io.open("a")
>    ...
>    if need_to_reopen_this_file then
>       f:close()
>       f = io.open(...)
>    end
>    ...
> end  -- evict the file value from f
> 
> Another possible situation - you are reading multi-volume archive.
> Only one volume file is opened at any given time.
> To switch a volume, you close the current volume file and open the next
> volume file.
> Single to-be-closed variable is enough to guarantee that the last opened
> volume file will be closed on eviction.

  The following worked:

	for i = 1 , 10 do 
	  local <toclose> f = io.open(string.format("volume.%d",i),"w")
	  f:write(tostring(i),"\n")
	end

  Only one file is open at a time.  So there is a way to kind of re-use a
closed variable.

  Now, the following kept the files open unil the end:

	local function process(i)
	  if i < 10 do
	    local <toclose> f = io.open(string.format("volume.%d",i),"w")
	    return process(i+1)
	  end
	end

  Just something else to keep in mind.

  -spc