Main Content

Passing multiple results back from a function - Lua, Python, etc

Archive - Originally posted on "The Horse's Mouth" - 2009-08-13 13:12:21 - Graham Ellis

Have you ever wondered why you can pass in as many parameters as you like to a function, but only return one? It seems rather unfair, doesn't it - especially as you may have lots of results.

In fact, in some languages such as Lua you can pass multiple values back:
  a,b,c = symie(4,7,9)
(see source code)

and in others such as Python and Perl you can return one collection which contains multiple items. Here's an example return in Python:
  return (net, tax)
and the code that collects the two return values from the function:
  shop, taxman = both(amount)
(see source code of function and caller).

Even less directly, you can return hashes, lists or objects in other languages, and in C you can return a pointer to a structure. Perl often sets special global variables (to take what I sometimes describe as 'side effect' results) which are all well and good if you know what is happening, and most languages allow some sort of global variable which is OK if used in extreme moderation!