lua-users home
lua-l archive

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


On Thu, 2021-09-23 at 09:48 +0200, Marc Balmer wrote:
> 
> function stat ()
>   local res <const>
> 
>   if cond == 1 then
>     res = db:exec('select * from whatever')
>   else
>     res = db:exec('select * from somethingelse')
>   end
> 
>   -- do something with res
> end
> 
> 
> 
> I can use a nested function:
> 
> function stat ()
> 
>   local function doSomething(res)
>     -- do something with res
>   end
> 
>   if cond == 1 then
>     local res <close> = db:exec('select * from whatever')
>     doSomething(res)
>   else
>     local res <close> = db:exec('select * from somethingelse')
>     doSomething(res)
>   end
> end
> 

(You used `<close>` instead of `<const>` in follow-up message, I'm
assuming this to be a mistake.)
I think it may be cleaner to write this instead:

function stat ()
  local function fetchResults()
    if cond == 1 then
      return db:exec('select * from whatever')
    else
      return db:exec('select * from somethingelse')
    end
  end

  local res <const> = fetchResults()

  -- do something with res
end

Alternatively, you can avoid declaring function at all by using ternary
operator (cond == 1 and ... or ...). You can also assign to non-const
local variable in condition and then assign *that* to const, but that's
not quite elegant.
-- 
v <v19930312@gmail.com>