lua-users home
lua-l archive

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


On 19 March 2018 at 19:08, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> I still think you are exaggerating the problem, but I may be wrong. I
> would like to know how many real programs have the construction
> t[k] = f() where f() returning 'nil' is not a bug.

I do that often.  for example, when generating code from a parsed AST,
 I usually append stuff in a table, calling several functions, either
from a loop (while walking the AST) or explicitly calling several
different functions (when taking each part of the meaning of a
fragment)  on each call, i just do `o[#o+1] = f()`, if the function
returns nil, nothing is appended to the `o` table.

similarly, to remove elements from a list, the "regular" way is

local o = {}
for i, v in ipairs(t) do
  if wanted(v) then
    o[#o+1] = v
  end
end

but sometimes it's easier to do:

local o = {}
for i, v in ipairs(t) do
  o[#o+1] = wanted(v) and v or nil
end

especially when the 'wanted(v)' function already returns `v` (or a
translation of it) or nil


-- 
Javier