How can I ignore first results from a function in Lua?

Thibault Falise picture Thibault Falise · Jul 2, 2010 · Viewed 9.3k times · Source

Lua functions can return multiple results :

a, b, c = unpack({'one', 'two', 'three'})

If I'm not interested in the third return value, I can choose to ignore it when calling the function :

a, b = unpack({'one', 'two', 'three'})

Is there a similar way to ignore the X first elements when calling the function ?

I could write this code if I only want the third return value, but I was wondering if a cleaner code exists :

_, _, c = unpack({'one', 'two', 'three'})

Answer

interjay picture interjay · Jul 2, 2010

You can use the select function. It will return all arguments after index, where index is the first argument given to select.

Examples:

c = select(3, unpack({'one', 'two', 'three'}))
b, c = select(2, unpack({'one', 'two', 'three'}))
b = select(2, unpack({'one', 'two', 'three'}))   --discard last return value

That said, I think in most cases, writing _,_,c = f() is cleaner. select is mostly useful when the argument number is not known in advance, or when chaining function calls together (e.g. f(select(2, g())))