lua-users home
lua-l archive

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



I've used 'false' in such cases, as table hole fillers.

Condition1 and C or D,
Condition2 and E or false,

Simple, but not perfect..


Alexander Gladysh kirjoitti 10.3.2006 kello 8.59:

Hi, all!

I need to create table (array), conditionally filled with elements.
Something like this (in pseudocode):

t =
{
  A,
  B,
  if Condition1 then C else D end,
  if Condition2 then E else nil end,
  F
}

Problem is that second 'if' would generate gap in array if Condition2
is false. Of course I can iterate over array after its creation, and
close the gaps, which I would like to avoid.

Furthermore, (looks like) Lua syntax does not allow if statements to
appear inside table constructor, so I would have to use helper
function.

local iff = function(b, l, r) if b then return l else return r end end;
t =
{
  A,
  B,
  iff(Condition1, C, D),
  iff(Condition2, E, nil),
  F
}

I see another way with manually specifying indexes in array like this:

local index = 1
local nextindex = function()
  local oldindex = index
  index = index + 1
  return oldindex
end

local iff = function(b, l, r) if b then return l else return r end end;
local iffc = function(b, l, r)
  if b then
    if l then index = index + 1 end
    return l
  else
    if r then index = index + 1 end
    return r
  end
end

t =
{
  [nextindex()] = A,
  [nextindex()] = B,
  [nextindex()] = iff(Condition1, C, D),
  [index] = iffc(Condition2, E, nil),
  [nextindex()] = F
}

In this way, if branch with nil is selected, index is not incremented,
and nil array entry gets overridden with next element (F in the
example). (And if there is no next element, then it would be discarded
by Lua itself, so it is ok.)

While such approach looks suitable for my machine-generated case, I
would like to find some more user-friendly technique.

Any advices?

Thanks in advance,
Alexander.