lua-users home
lua-l archive

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


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.

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.