Returning multiple values from a function - Lua
Archive - Originally posted on "The Horse's Mouth" - 2010-04-15 06:36:53 - Graham EllisDoes it strike you as odd that in many languages, functions can take in as many parameters as you like, but can only return one? Of course, you can return a single collection object (list, array, tuple, dictionary, hash, Vector, object ...) or set up global variables to hold side effect results if you wish. But in Lua, you can truly return multiple values:
function food()
return "carrots","peas","gravy","haggis","neaps","tatties"
end
Individual results can be assigned to a series of individual variables, left to right, with any excess or results being discarded. And Lua's use of the variable "underscore" - _ - as a convention of a place filler - can be used to skip over unwanted intermediates if you have any:
first,second,_,fourth = food()
print (first,second,fourth)
If you want to know how many values you're getting back, or to get one back by numbered position, there's a built in select function in Lua:
-- Give me the number of return parameters
iwant = select("#",food())
print (iwant)
-- Give me the third return parameter
iwant = select(3,food())
print (iwant)
One slight 'issue' - if you bring back a multiple result and then use it straight away in another function call, only the first result will be passed on if there are other parameters following. Let me show you that behavior, as it can be a "catch" the first time:
print (food(),food())
gives you
carrots carrots peas gravy haggis neaps tatties
That's a nice meal, but we're apparently missing a portion of peas, gravy, haggis, neaps and tatties - but have plenty of carrots.