3

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).

wimalopaan
  • 4,838
  • 1
  • 21
  • 39
  • 5
    I'm not sure if it's possible but maybe just adding `_ = nil` on the next line is the best alternative – Ivo Oct 28 '21 at 08:22
  • @IvoBeckers that's definitely the simplest solution. the cases where this is actually necessary should be very very rare. – Piglet Oct 28 '21 at 08:50

2 Answers2

4

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());
Ivo
  • 18,659
  • 2
  • 23
  • 35
  • 2
    Or `function firstAndThird(a,b,c) return a,c end` to avoid creating a table. – lhf Oct 28 '21 at 09:05
  • @lhf yeah that's even better. don't know why I didn't think of that haha. I'll edit my answer to make it like that – Ivo Oct 28 '21 at 09:31
3

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
Piglet
  • 27,501
  • 3
  • 20
  • 43
  • I think some newlines would improve your code a lot. At first I didn't get the syntax you used in the first example, until i realised I would write the same code over several lines if I wrote it myself. Putting everything on one line can be nice at times but it shouldn't cause any confusion. But what's suitable as one-liner or not is of course a bit subjective. – Ivo Oct 28 '21 at 10:01
  • 1
    @IvoBeckers the only time I use a one-liner per year and you catch me :D – Piglet Oct 28 '21 at 10:22