lua-users home
lua-l archive

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


Hi!

I have a problem while trying to use a to-be-closed variable as usual upvalue.
An upvalue's lifespan might go beyond the current block, and the lifespan is unknown at compile time.
This is a code of simple Lua program to explain the problem:


local say = print

local function log_start_time()
   local logfile <close> = assert(io.open("log.txt", "a"))

   local function write_to_log(msg)
      logfile:write(msg.."\n")
   end

   write_to_log("Started at "..os.date())
   -- Usually, only start time is written to the log
   -- Unless user specified "--log-everything" option
   if arg[1] == "--log-everything" then
      -- All messages to say() must go also to the log
      function say(msg)
         print(msg)
         write_to_log(msg)
      end
      -- Now I want the file to remain opened after exiting from the current function
      -- I need to de-<close>-ify the variable "logfile"
      -- How can I do that?
   end
end

log_start_time()
say("Hello")
say("Result = "..some_long_time_calculations())
say("Bye")