So I'm still a somewhat beginner and I'm getting better at Lua but I'm still confused on 2 things. I still somewhat don't get "for i, v" and what doing that does. Same with how arrays are used in games. If someone can give an example with their explanation that would be great.
A for
loop does something for each thing in some collection.
It looks like this:
for <values> in <collection> do -- do THIS STUFF for each <value> in the <collection> end
For example, pretend you've defined a list of colors:
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)
local colors = {BrickColor.Red(), BrickColor.Blue(), BrickColor.Yellow()} 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:
local colors = {BrickColor.Red(), BrickColor.Blue(), BrickColor.Yellow()} for index, color in pairs(colors) do local part = Instance.new("Part", workspace) part.BrickColor = color part.Position = Vector3.new(0, index, 0) end
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:
for _, player in pairs(game.Players:GetPlayers()) do -- kill each player's character player.Character:BreakJoints() end