[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Expanding multiple return values of Lua functions in a Lua table constructor
- From: Michal Kottman <k0mpjut0r@...>
- Date: Wed, 17 Oct 2012 21:37:24 +0200
On 17 October 2012 21:28, agentzh <agentzh@gmail.com> wrote:
> Hello, folks!
>
> Sorry if this is a FAQ. I'm stumbling on the following example with
> Lua 5.1.4 and 5.1.5:
>
> $ lua -e 'function foo(a) return a, "d" end local tb = {
> foo("ab"), foo("c") } print(table.concat(tb))'
> abcd
>
> Why is the output neither "abdcd" nor "abc"? Why is the second return
> value of the first foo() call swallowed by the table constructor while
> the second foo() call is not?
Quoting the manual [1]:
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, discarding all values except the first
one.
[1] http://www.lua.org/manual/5.2/manual.html#3.4
This means that only the last (final) call is expanded to all values,
all other are adjusted only to the first value. This means that you
get "ab" from the first call of foo, and "c" and "d" from the second
call of foo.
If you wrote this: local tb = { foo("a"), foo("b"), foo("c") } you
would also get "abcd", because the first two will return only one
value, and the last will return "c" and "d".