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'})
Use os. exit() or just return from some "main" function if your script is embedded.
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.
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.
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.
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()))
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With