[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to convert to-be-closed variable to normal one in runtime?
- From: Mimmo Mane <pocomane_7a@...>
- Date: Tue, 21 Jul 2020 16:27:21 +0200
On Tue, Jul 21, 2020 at 1:19 PM Egor Skriptunoff wrote:
> 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.
...
> -- 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?
Normally, you can declosify just overriding the __close() metamethod,
but here it is impossible without affecting the other files. You can
still use the proxy trick suggested by Andrew, or invert the logic:
```
local say = print
local function log_start_time()
local logfile = assert(io.open("log.txt", "a"))
local function write_to_log(msg)
logfile:write(msg.."\n")
end
write_to_log("Started at "..os.date())
if arg[1] ~= "--log-everything" then
local please <close> = logfile
else
function say(msg)
print(msg)
write_to_log(msg)
end
end
end
```
About the sub-scope trick: in this case it would be simpler to just
call file:close() or getmetatable().__close(), however in some cases
you just can do it (`getmetatable().__metatable = "Not your buisness"`
with an ad-hoc __close() metamethod).