lua-users home
lua-l archive

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


> "Tom Miles" <Tom@creative-assembly.co.uk> writes:
>
> > Okay, so I'm obviously missing something with this.  Can anyone
> > explain the behaviour from this:
> >
> > function test1()
> >     return 1, 2
> > end
> >
> > function test2()
> >     return 3,4
> > end
> >
> > print(test1(), test2())
> >
> >> 1    3    4
> >
> > I would have expected it to output 1    2    3    4.  Why doesn't it?
>
> Only the last function in a comma list has multiple return values
> respected.

On 9/12/07, Tom Miles <Tom@creative-assembly.co.uk> wrote:
> Is there a good reason for that?  I assume there is, but I'ld like to
> know, as it seems a bit counter-intuitive.

At first sight, it's counter-intuitive.
Think about how you'd write the print() function so that it took
multiple variadic arguments(??).

in your example "print(test1(), test2())", if the output was "1 2 3
4", from the standpoint of print(), what part of the output is the
first argument, what part is the rest? How would you write such a
function in Lua?

-- count & print the arguments one per line
function myprint(...)
   for i,v in pairs({...}) do
      io.write(i .. ":  " .. v .. "\n")
   end
end

myprint(test1(), test2())
1:  1
2:  3
3:  4

So, I guess you're hoping the expansion of "print(test1(), test2())"
would be "print(1,2, 3,4)" but that would be rather difficult to
handle for anyone writing variadic functions - consider


function variadic(a, b, ...)
   print(a, b, ...)
end
variadic(test1(), test2())

What should be in a? what should be in b?

-K

PS. Top-posting and HTML-encoded messages are generally accepted as no-noes.