lua-users home
lua-l archive

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


Alternatively:
> local x <const> = cond and db:query('select * from whatever') or db:query('select * from something else')
This is similar to the ternary operator in other languages, the only drawback being if the "then" branch is falsy then it always evaluates to the "else" branch.
If `query` returns a table type, then this might suffice here.


On Fri, 24 Sept 2021 at 07:45, Philippe Verdy <verdyp@gmail.com> wrote:
Why not:

function stat()
   local function doSomething(query)
      local res <const> = db:exec(query)
      -- do something with res
   end
   if cond == 1 then
       doSomething( 'select * from whatever')
   else
      doSomething('select * from somethingelse')
   end
end
-- here the res can be <const> as you want and as well <toclose> for being closed at end of doSomething())

Or:

function stat()
   local function makeQuery()
       if cond == 1 then
           query =  'select * from whatever'
       else
           query = 'select * from somethingelse'
       end
   end
   local function doSomething(res)
      -- do something with res
   end
   local qry <const> = makeQuery()
   local res <const> = db:exec(qry)
   doSomething(res)
end
-- here the res and query can both be <const>, and as well both declared <toclose> for being closed at end of stat()

Or a bit more compactly:

function stat()
   local function doSomething(res)
      -- do something with res
   end
   local qry <const> = (function()
       if cond == 1 then
           return  'select * from whatever'
       else
            return 'select * from somethingelse'
       end
   end)()
   local res <const> = db:exec(qry)
   doSomething(res)
end

Or very compactly:

function stat()
   (function(res)
      -- do something with res
   end)(db:query((function()
       if cond == 1 then
           return  'select * from whatever'
       else
            return  'select * from somethingelse'
       end
   end)()))
end

Le jeu. 23 sept. 2021 à 09:48, Marc Balmer <marc@msys.ch> a écrit :
> 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.