Answered by
8 years ago Edited 8 years ago
A for
loop does something for each thing in some collection.
It looks like this:
1 | for <values> in <collection> do |
For example, pretend you've defined a list of colors:
1 | local colors = { BrickColor.Red(), BrickColor.Blue(), BrickColor.Yellow() } |
You want to create one part of each color and make a stack of those parts.
In other words, for each color
in colors
, you want to do something.
Lua needs a little help explaining what "each" means on a list. You use pairs(colors)
in order to get each index and value in the list. The index
is such that colors[index]
is the color
you want (index
goes 1, 2, 3 and color
goes red, blue, yellow)
1 | local colors = { BrickColor.Red(), BrickColor.Blue(), BrickColor.Yellow() } |
3 | for index, color in pairs (colors) do |
Let's make a part that's colored color
and at position Vector3.new(0, index, 0)
so that they stack:
1 | local colors = { BrickColor.Red(), BrickColor.Blue(), BrickColor.Yellow() } |
3 | for index, color in pairs (colors) do |
4 | local part = Instance.new( "Part" , workspace) |
5 | part.BrickColor = color |
6 | part.Position = Vector 3. new( 0 , index, 0 ) |
Arrays
Arrays are used all of the time! If you have more than one of a type of thing (more than one player, more than one enemy, more than one attack, more than one projectile), you'll probably need an array of all of those things!
For example, you can get all of the players in a game using game.Players:GetPlayers()
. This returns an array.
You can do something to each player by using a for
loop with it:
1 | for _, player in pairs (game.Players:GetPlayers()) do |
3 | player.Character:BreakJoints() |