[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: One time assignment to to-be-closed variiable
- From: Francisco Olarte <folarte@...>
- Date: Thu, 23 Sep 2021 13:04:11 +0200
Marc:
On Thu, 23 Sept 2021 at 09:39, Marc Balmer <marc@msys.ch> wrote:
> Is it somehow possible to make one time assignment to a to-be-closed variable? E.g. something like this:
> local res <const>
> if cond == 1 then
> res = db:exec('select * from whatever')
> else
> res = db:exec('select * from somethingelse')
> end
> Or is it so that to-be-closed variables can only be assigned a value during creation?
> If the latter: It would be useful to allow for one time assignment to to-be-closed variabled.
I think Java allows it, in C++ which does not I use the private file
function returning the value trick. This can be extended in lua to use
a nested function or even an anonymous one, both of which have the
advantages over C of seeing local vars IIRC. Seems to work for me in
this little dirty example:
Lua 5.4.3 Copyright (C) 1994-2021 Lua.org, PUC-Rio
> closemt = { __close = function(s) print("closing",s[1]) end }
> closer1 = setmetatable({1}, closemt)
> closer2 = setmetatable({2}, closemt)
> a=true
> local x <close> = (function() return a and closer1 or closer2 end)(); print (x[1]);
1
closing 1
> a=false
> local x <close> = (function() return a and closer1 or closer2 end)(); print (x[1]);
2
closing 2
Francisco Olarte.