Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do you use the select() function and what is its purpose?

Asked by 5 years ago
Edited 5 years ago

I've read from the Wiki that select() is used to return arguments in one of two ways: either the total number of arguments (int) or a tuple of arguments after a given index number. However, I don't get the point of doing this:

select(1, unpack(game.Players:GetPlayers()))

versus doing this:

select("Player1", unpack(game.Players:GetPlayers()))

If somebody can tell me how I can use this function, that would be a pleasure.

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

select is used for getting either the amount of arguments by provided (if the first argument is "#"), or to get all arguments after the n-th argument.

An example of using select to get amount of arguments:


function amountArguments (...) return select("#", ...) end local arguments = amountArguments(1,2,3,4, "five"); print(arguments) --> 5

An example of using select to get the arguments after n

print(select(2, "a", "b", "c")) --> "b" "c"

An example use case is to have a function that sums up all arguments and divides them by the amount of arguments.


function getAverage (...) local sum = 0; local totalArguments = select("#", ...); for x = 1, totalArguments do sum = sum + select(x, ...) end return (sum / totalArguments); end local ageAverage = getAverage(15, 16, 12, 9, 8, 15, 13, 14, 14, 16, 19) print(ageAverage) --> 13.727272727273
Ad

Answer this question