Diego Sacconi
Diego Sacconi

Reputation: 120

Why Lua adjusts the results in this way?

I'm reading the Lua Reference Manual and it says:

Both function calls and vararg expressions can result in multiple values. [...] If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, discarding all values except the first one.

What are the advantages of this choice?

Is it common to other programming languages?

Upvotes: 2

Views: 193

Answers (2)

siffiejoe
siffiejoe

Reputation: 4271

On one hand, if you support multiple return values, you probably want something like the following work:

local x, y, z = a()

On the other hand, without the the current rule, the following code

local x, y, z = b(), c()

is very hard to analyze: x, y, and z could hold the return values of b() if it returns at least 3 values (c()'s return values are dropped completely in this case), or they could only hold the return values of c() (padded filled with nils) if b() does not return any values at all, or various combinations thereof. Note that the number of return values of functions can vary depending on circumstances.

With the current rule x always gets the first return value (which is often the most important) of b() (or possibly nil if b() doesn't return any), y always gets the first return value of c() (or nil), and and c gets the second return value of c() or nil. Nice and easy, and the first use case above is covered as well.

So the reason is that it's easier to decipher just by looking at the assignment which variable gets which return value. It's the same for function calls, btw.:

function f( x, y, z )
  -- ...
end

f( b(), c() )

Upvotes: 1

luther
luther

Reputation: 5544

Other languages that allow vararg functions and multiple return values usually require you to be more explicit. They don't have a silent shortcut for getting the first item, as Lua does. Here are some possible reasons for doing it the Lua way:

  • Probably the most important reason is that it's possible to get the number of explicit items from multiple values, even if they end in nil. See select and table.pack. Implicit conversion to a table would lose this information.
  • You can add a second value to a return statement without breaking backward compatibility. Otherwise, the calling code would have to change in order to access the first return value.
  • Sometimes, the second return value is an error message. Lua lets us ignore the error by pretending the function has just one return value. (Although this is probably a downside, not an advantage.)
  • There may be other advantages to the syntactic sugar that I haven't thought of.

Upvotes: 2

Related Questions