Reputation: 120
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
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 nil
s) 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
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:
nil
. See select
and table.pack
. Implicit conversion to a table would lose this information.return
statement without breaking backward compatibility. Otherwise, the calling code would have to change in order to access the first return value.Upvotes: 2