Tuples are mostly used as a list of arguments.
If you've ever seen the following syntax:
...
This is called 'vararg', and represents a tuple. Functions like print can be called with any number of arguments:
print("a")
print("a", "b")
print("a", "b", "c")
etc.
That's because print, by default, accepts a tuple (represented by the vararg syntax ...) as arguments.
Heres a simple way to use the vararg operator:
local team1 = {}
function addToTeam1(...)
local player_tuple_table = {...} --"Pack"ing the tuple into a table
for i = 1,#tuple_table do
table.insert(team1, player_tuple_table[i])
end
end
As you can see, you can't access members directly from a tuple, it has to be put in some other form (such as a table.) You can also list other arguments, but the vararg must be at the end, like so:
function removeFromTeam(team, ...)
if not team then print("Give me a team to remove from!") return; end
local player_tuple_table = {...}
for i = #team,1,-1 do
for j = 1,#player_tuple_table do
if team[i]==player_tuple_table[j] then
table.remove(team, i)
table.remove(player_tuple_table, j)
break;
end
end
end
end
Some things you can do with tuples using the select function are as follows:
--Get how many elements make up the tuple
function getAmountOfArguments(...)
local amount = select("#", ...)
return amount
end
print(getAmountOfArguments("One argument"))
print(getAmountOfArguments("First", "Second", 3, false))
print(getAmountOfArguments()) --No arguments = 0
--Select a certain element from the tuple
function getTuple()
return "First", "Second", 3, false --Multiple returns = a tuple
end
print(select(4, getTuple())) -- >false
print(select(3, getTuple())) -- >3 false (notice all tuple elements after 3 will remain, this is the behavior of the select function)
print(select(2, getTuple())) -- >Second 3 false (all tuple elements after 2 also kept)
--Note: none of these snippets are tested. |