lua-users home
lua-l archive

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


This is just normal Lua vararg handling; string.format is no exception here. Varargs are always truncated to exactly one value - their first value, or nil if there is no first value - if they appear anywhere but at the end of an argument list. Examples:

function varg3() return 1, 2, 3 end
function varg0() return end
print(0, varg3()) -- 0, 1, 2, 3 -- not truncated
print(varg0(), varg3()) -- nil, 1, 2, 3 -- varg0() is truncated to nil
print(varg3(), varg0()) -- 1 -- varg0() is not truncated to nil, but varg3() is truncated to 1
print(0, varg3(), varg3(), 2) -- 0, 1, 1, 2 -- varg3() is truncated to 1 both times
On 25.11.22 23:56, bil til wrote:
PS: The following also might be interesting:
do
function Test() return 3, 5 end
s= string.format( "%d %d", Test(), 4)
end
s
3 4

... so it looks like the '...' of string.format somehow keeps only the
first return value of Test, except if Test function is the last
parameter... . Is this normal?

(I thought, that for such "further parameter stripping" it would be
required to specify this explicitely by brackets like in s=
string.format( "%d %d", (Test()), 4)? (this gives the same as above,
in this case it is clear to me...).

Am Fr., 25. Nov. 2022 um 23:46 Uhr schrieb bil til <biltil52@gmail.com>:
If I do the following in Lua 5.4:
do
function Test() return 3, 5 end
s= string.format( "%d %d %d", 4, Test())
end
s
4 3 5
... this is as expected...

do
function Test() return 3, 5 end
s= string.format( "%d %d %d", Test(), 4)
end
stdin:3: bad argument #4 to 'format' (no value)
stack traceback:
        [C]: in function 'string.format'
        stdin:3: in main chunk
        [C]: in ?
... this somehow does NOT work as I would expect... (I would expect
that s now is '3 5 4')

(if I debug with breakpoint in str_format, then the top of stack ( int
top = lua_gettop(L);) is only 3 in this last case... in first case it
is 4 as expected.... .

Is this some error of Lua, or do I miss here something?