Repeat function X times

Hi, so I want to find out how to repeat a function X times.

Lets say i need 3 players to fill the game and I only have 1 in the game, and I want to 2 or 1 more people (basically X) so I want to repeat a funciton that gets a random player in game, and if I need one player i want it to repeat 1 time and if i need 2 then i want the function to execute 2 times.

Hope you understood what I meant.

2 Likes

Welp a very simple answer: for loops
Always remember that the idea behind for loops, is a loop that loop a certain amount of times.

local needed_players = 4
for i = 1, needed_players - #game.Players:GetPlayers(), 1 do
   function
end

#game.Players:GetPlayers() is how many players there currently are, needed_player is how many we need to start, we will loop the for loop from how 1 to how many players are still needed (needed_players - #game.Players:GetPlayers())

2 Likes
function repeat(functionhere,amount)
for i = 1,amount do
functionhere(arguments)
end
end
3 Likes

Thanks for the help! @starmaq @twinqle

2 Likes

Going to plug-in: if you’d like to turn this function into a reusable one so that you can use it with any kind of scenario, I suggest that you incorporate varargs. That way, you can pass the function as well as any number of arguments. This scales well, whereas hardcoding arguments limits your options.

You should also not use repeat as a function name. It is non-descriptive towards the intention of the function, leads to a bad practice concept named variable shadowing (the word repeat is reserved for a keyword) and it’ll cause a syntax error.

local function repeatFunction(amount, functionBody, ...)
    for i = 1, amount do
        functionBody(...)
    end
end

Small edit to my post in regards to below.

2 Likes

Good point. I assumed he was using the same function but it’s always good to be efficient.

2 Likes

repeat can’t be used as a variable name because it’s a keyword, doing so should cause a syntax error.

i.e

local function repeat()

end

isn’t valid

This is a valid point too. I’ve added it to my post.

Worth also plugging in that other globals* are able to be used as function names, but shouldn’t be. In the case of repeat, yes it would cause a syntax error due to its nature as a keyword. On the other hand, using a global variable as a function name will not error but will run into the aforementioned problem (variable shadowing).

It’s always best to use your own names for functions and make them short-but-descriptive enough to get across what it’s responsible for handling, without using the same name as a global or keyword.

*

local function table()
    print("hi")
end

table()
-- Does not cause a syntax error, but now table points to the above function