lua-users home
lua-l archive

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



On 18-Oct-05, at 1:24 AM, Glenn Maynard wrote:

The problem is that design of the language, in this area, is unintuitive and unnatural to me. The multiple-results documentation in PiL reads like a checklist of special cases to be memorized. I'm not saying it's something
that should or could be changed; it just feels forced.

PiL says:

1) Lua always adjusts the number of results from a function to the circumstances of the call.

2) When we call a function as a statement, Lua discards all of its results.

3) When we use a call as an expression, Lua keeps only the first result.

4) We get all results only when the call is the last (or the only) expression in a list of expressions.

It seems pretty clear to me. The short summary (leaving out the obvious case of function call statements) is:

1) Lua expects an expression to yield exactly one value except when the expression is the last (or only) expression in an expression-list, in which case it yields all of its values.

2) Expression lists (as a whole) are adjusted to the context of an expression list, by either discarding extra results, or by appending a sufficient number of nils.

Rule 2 means that:

a, b = foo()

will adjust foo() to 2 return values, since clearly two values are expected (and since foo() is the only expression in an expression list.)

The one apparent exception to this is numeric for statements, because "a,b,c" in:

  for i = a, b, c

is not grammatically an expression list. (It is <expr> "," <expr> ["," <expr>] )

Normal value adjustment would result in the last value being nil rather than 1 if the rule were applied literally, but possibly it would be less surprising if

  for i = ...

were valid, with the third value being treated as 1 if it were nil (and possibly the second value being treated as the first value.)