lua-users home
lua-l archive

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


On Wed, Jul 27, 2016 at 5:36 PM, Peter Aronoff <telemachus@arpinum.org> wrote:
> Philipp Janda <siffiejoe@gmx.net> wrote:
>> Am 27.07.2016 um 19:16 schröbte Nagaev Boris:
>> > Why does it print "nil, nil" and not "nil, nil, nil"?
>>
>> As Daurnimator already indicated, no return value is a special case of
>> multiple return values: In certain situations multiple (or no) values are
>> coerced into one value, in other situations, like at the end of an
>> expression list, they are taken as is. All `print()` calls return no
>> value, but only the last call is the last expression of an expression
>> list, so the other two calls are coerced to one `nil` value each.
>
> I apologize if I’m being dense, but I still don’t follow. I’m going to try
> to say what I understand. If anyone can correct or expand, I appreciate it.
>
> 1. print() calls return no value
> 2. In a list of expressions, multiple or no value returns are taken “as
>    is”. (I don’t really see what “taken as is” means, to be frank.)
> 3. print(1), print(2), print(3) is an expression list.
> 4. So, (per (2)), the first two (only?) print() calls are taken “as is”.
>    The two `nil`s come from that. I.e., they are coerced to display their
>    not having a return value by displaying `nil`?
>
> If all that is right, my remaining question: why isn’t the last call in
> an expression list also taken “as is”. I.e., once again, why not `nil, nil,
> nil`?
>
> Thanks, Peter
> --
> We have not been faced with the need to satisfy someone else's
> requirements, and for this freedom we are grateful.
>     Dennis Ritchie and Ken Thompson, The UNIX Time-Sharing System

It's the other way around.

The first two AREN'T being taken as-is. They're being used in an
expression context instead of an argument list context, and in an
expression context an empty arg list is coerced to nil.

The last one is an argument list context, and therefore the rest of
the value list is replaced with the last print()'s return value list.

If it helps, consider this:

function test()
  return 1, 2, 3
end
print(test(), test(), test())

This outputs "1 1 1 2 3" for the same reason -- the first two calls
are coerced to a single value, but the last one is expanded as
multiple arguments.

/s/ Adam