lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi Perry,

just a slight correction: in a statement such as (say f() returns 3 values):

a, b, c = f(), x -- the result of f is indeed adjusted to 1 value, however 
a, b, c = x, f() -- the result of f is also adjusted but to 2 values now and
a, b, c, d = x, f() -- now all 3 values of f() are used

This is explained in section 3.3.3 - Assignment:

> Before the assignment, the list of values is adjusted to the length of the 
list of variables. If there are more values than needed, the excess values are 
thrown away. If there are fewer values than needed, the list is extended with 
nil's. If the list of expressions ends with a function call, then all values 
returned by that call enter the list of values, before the adjustment (except 
when the call is enclosed in parentheses; see §3.4). 

To follow up on your question
> 
> The text is consistent.  The text says that if the function call is the
> last, then all of the values returned are used.  But doesn’t actually say
> what happens if it isn’t the last element (unless I missed it).
> 

Have a look at section 3.4 Expressions, paragraph 3:

> Both function calls and vararg expressions can result in multiple values. If 
a function call is used as a statement (see §3.3.6), then its return list is 
adjusted to zero elements, thus discarding all returned 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 expression is enclosed in parentheses). 
In all other contexts, Lua adjusts the result list to one element, either 
discarding all values except the first one or adding a single nil if there are 
no values. 

The last sentence is important here:  "In all other contexts, Lua adjusts the 
result list to one element, either discarding all values except the first one 
or adding a single nil if there are no values. "

Note that this also means that if f() returns nothing, then given the 
expression:

a, b = f(), x

a is nil and b has the same value as x.

I suppose the rules here exist to allow very easy association of the 
initializing expressions with each binding. So in any case you can easily tell 
that a gets initialized from f() and b from x regardless of how many values 
f() actually returns.

Hope this helps!

Sebastian