Im learning about for loops and I get that it repeats a block of code a set number of times I understand what it does but why? where would we use this in a game?
You’ve got a list of players and you want to do something with each player. First thing is first, you need to get a list of the players using GetPlayers. Then let’s say we want to print every player in the game.
local players = game.Players:GetPlayers()
if players[1] then
print(players[1].Name)
if players[2] then
print(players[2].Name)
if players[3] then
print(players[3].Name)
if players[4] then
print(players[4].Name)
...
That works but it’s ugly, hard to read, and impossible to maintain. Plus, we need to repeat this up to our max server size. Imagine this extended out to a twenty player server. Imagine instead of printing their name, I’m doing something that takes more than one line of code. It would be a nightmare.
Or I can use a loop.
for index, player in game.Players:GetPlayers() do
print(player.Name)
end
Numeric for loops are also useful. Imagine if you want a countdown like this:
print(10)
wait(1)
print(9)
wait(1)
print(8)
wait(1)
print(7)
...
Once again it’s ugly and hard to maintain. Also we can’t just change how much time the timer takes. With a loop, we can fix all of this.
local start_time = 10
for time_left = start_time, 1, -1 do
print(time_left)
wait(1)
end
Imagine you’re making a disaster game and you want three meteors to spawn above every player.
local players = game.Players:GetPlayers()
if players[1] then
if players[1].Character then
-- spawn a meteor
-- spawn another meteor
-- spawn a third meteor
end
if players[2] then
if players[2].Character then
-- spawn a meteor
-- spawn another
-- spawn another
end
...
Again, ugly, hard to maintain. Imagine some update breaks the meteor spawning or something. You now need to go into your code and change it in 20 players times 3 meteors each = 60
locations. To change it to four or five meteors you need to go and copy+paste some code in 20 locations.
Or do this.
for index, player in game.Players:GetPlayers() do
if player.Character then
for i = 1, 3 do
-- spawn a meteor
end
end
end
Very Informative Thank You So Much!
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.