Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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'}) 
like image 264
Thibault Falise Avatar asked Jul 02 '10 13:07

Thibault Falise


People also ask

How do you exit a function in Lua?

Use os. exit() or just return from some "main" function if your script is embedded.

Can Lua function return multiple values?

Lua Functions Multiple resultsFunctions in Lua can return multiple results. Variable a will be assigned the first return value and the remaining two will be discarded. This way, one can iterate over the results table to see what the function returned.

How do you return a value from a function in Lua?

Function return values In most languages, functions always return one value. To use this, put comma-separated values after the return keyword: > f = function () >> return "x", "y", "z" -- return 3 values >> end > a, b, c, d = f() -- assign the 3 values to 4 variables.

How many functions does Lua have?

This means that all values can be stored in variables, passed as arguments to other functions, and returned as results. There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table.


1 Answers

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

like image 183
interjay Avatar answered Oct 19 '22 04:10

interjay