lua-users home
lua-l archive

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


On Thu, 23 Sept 2021 at 09:39, Marc Balmer <> 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, 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]);
closing    1
> a=false
> local x <close> = (function() return a and closer1 or closer2 end)(); print (x[1]);
closing    2

Francisco Olarte.