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

Explanation for Certain Things Like For and Arrays?

Asked by 8 years ago

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.

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago
Edited 8 years ago

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

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
0
So your saying in the for loop the "player" and "color" can be named anything just like functions can be named anything right? Other than that you explaned everything else great! Thanks for the help. Retr0Thief 104 — 8y
0
Right, they're just variable names that you pick. "i" is short for index and "v" is short for value so lots of examples use those names, but I personally like longer, more descriptive names. BlueTaslem 18071 — 8y
Ad

Answer this question