In less specific terms, "tuples" are a general extension of "pairs": ordered sequences of things with known length.
Tuples are a really weird and a really nice feature of Lua.
The simplest way that tuples show up is multiple assignment:
apple, banana = 5, 13
print(apple)
print(banana)
Lua matches up each thing on the left with a thing on the right.
This goes deeper than that though. We can return multiple things from a function:
function gets()
return 7, 17
end
apple, banance = gets()
print(apple)
print(banana)
Though doing anything to the result will make it only keep the first one:
apple, banana = gets() + 1
print(apple)
print(banana)
We can use a few, too:
apple, banana, cat, dog = gets(), gets()
print(apple, banana, cat, dog)
Here, they start where the function started on the right, and the ones to the right "cover up" the ones to the left.
Hence apple is the first result of the first gets(), banana is the first result of the second gets() and cat is the second result of the second gets().
We can also use these in definitions of lists:
local t = {1, gets()}
print(t[1], t[2], t[3])
These are basically just conveniences. There is an interesting function: unpack.
local list = {4, 5, 6}
local x, a, b, c = 1, unpack(list)
print(x, a, b, c)
This essentially "un-does" the operation of putting tuples inside of a table. ie.
list = { unpack(other) }
Will have the same contents as list other.
Consider a function that adds two numbers:
function sum(a, b)
return a + b
end
What if I want to add more than two numbers?
print( sum(1, sum(2, 3)) )
This isn't very nice; what if we add a third parameter?
function sum(a, b, c)
return a + b + c
end
print( sum(1, 2, 3) )
print( sum(1, 2) )
So now we have to change this to support c being option:
function sum(a, b, c)
return a + b + (c or 0)
end
What if we wanted to add 4 numbers? Now this starts to get messy. One option is that we instead take a list of numbers:
function sum(list)
local s = 0
for _, el in pairs(list) do
s = s + el
end
return s
end
But now we can't say sum(1, 2), we have to say sum({1, 2}). What is the solution? Tuples!
function sum(...)
local list = {...}
for _, el in pairs(list) do
s = s + el
end
return s
end
Basically, ... is a variable -- except it is a tuple, rather than only one value.
Thus list = {...} will make a list filled with the same arguments that were passed to sum!
For good measure, here's a way to use ... that doesn't involve immediately dumping it into a table:
function sum(first, ...)
if not first then
return 0
end
return first + sum(...)
end