LUA: howto omit a value of a multi-value in a multiple-assignment

97 Views Asked by At

If I want only the first and the third value of the function f(), I can do the following:

local a, _, b = f();

Since _ is a valid name, maybe _ gets assigned a large table.

Is there a way to omit this assignent to _ in the above case? (Clearly: if _ goes out of scope it is gc'ed).

2

There are 2 best solutions below

2
Ivo On

Not sure if it helps but maybe you can define a helper function like

function firstAndThird(a, b, c)
    return a, c
end

and then use it like

local a, b = firstAndThird(f());
2
Piglet On

Is there a way to omit this assignent to _ in the above case?

No there is no way to omit that assignment if you need the third return value. You can only make sure not to keep the returned object alive by referring to it through _. Of course this only makes a difference if there is no other reference left.

In addition to using a function to limit _'s scope you can also use do end

local a,c
do
  local _ a,_,c = f()
end

or you simply remove the unused reference.

local a, _, c = f()
_ = nil