So I've seen many scripts with tuples (The three periods). I have looked at the wiki and YouTube tutorials on them, but I still have not even the slightest clue on their functions, or what they even are. Can somebody clear this up for me? Thank you.
What are tuples, and how do they work?
1 answer
This is a tricky topic because of the weird ways it appears in Lua.
Tuples are basically sequences of values not bound into a table.
Tuples in Assignment
Here is the simplest use of tuples:
a, b = 1, 2
print(a) -- 1
print(b) -- 2
In assignment, a tuple (values separated by commas) are assigned to the respective variables at the left.
Tuples in Return
This also applies to functions which return multiple values:
function two()
return 1, 2
end
a, b = two()
print(a) -- 1
print(b) -- 2
Or, for that matter,
print( two() )
-- 1 2
A warning; if you do any math to the values, you will lose all but the first:
a, b = two() * 3
print(a) -- 3
print(b) -- nil
Passing Tuples to Functions
You can also use tuples as function arguments:
print(two())
-- 1 2
function sum(a,b)
return a + b
end
print( sum(two()) -- 3
Making Tables with Tuples
You can also use tuples with tables:
t = {3, two()}
print( table.concat(t, "\t") )
-- 3 1 2
A warning: if you put something after the value, you'll "cover up" the previous ones:
t = {3, two(), 4}
print( table.concat(t, "\t") )
-- 3 1 4
...Though if there were more it would continue:
function three()
return 5, 6, 7
end
t = {3, three(), 4}
-- 3 5 4
Unpack
Finally, there are the two ways to deal with this in general.
You can use unpack(tab) to turn a list tab into a tuple, e.g.,
five, seven = unpack( {5, 7} )
Varargs (...)
Or, you can use ... as the function parameter to get the list of things coming in:
function things( ... )
local list = {...}
-- Fills `list` with parameters (just like tuples in the previous examples)
local sum = 0
for i = 1, #list do
sum = sum + list[i]
end
return sum
end
print( things( 5, 1, 2) ) -- 8
print( things( 1, 2, 3, 4, 5, unpack( {1, 2} ) ) )
-- sums 1 + 2 + 3 + 4 + 5 + 1 + 2 =
-- 18
This lets you make variadic functions -- functions which can use any number of arguments, without you deciding the exact number ahead of time.
Anything you want me to expand on or detail further, let me know and I'll add to this answer.
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
Correction: t = {3, three(), 4} > 3, 5, 4
oops