Amusing behavior '...' in Lua

50 views Asked by At

It's not a problem. Just Lua is amazing.

t = {1, 2, 3}
print(table.unpack(t))     -->1 2 3
print(0, table.unpack(t))  -->0 1 2 3
print(table.unpack(t), 4)  -->1 4

What?

1

There are 1 answers

0
CHlM3RA On

The problem boils down to assigning values to variables, let me simplify the question:

function ret_1_2_3()
    return 1, 2, 3
end

f, g, h, i = 0, ret_1_2_3()
print(f,g,h,i)                  --> 0   1   2   3
f, g, h, i = ret_1_2_3(), 4
print(f,g,h,i)                  --> 1   4   nil nil

You don't have to give the variables a name when using "..." but it's following the same rules and table.unpackreturns multiple values. In the Lua 5.2 Reference Manual under point 3.4 it says:

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, either discarding all values except the first one or adding a single nil if there are no values.

I did take me a while to figure that out, it's a good question you asked there.