I have a question about i, v in pairs
About different types and what makes them different (maybe when I should use them too)
I will be using GetChildren() as the example
I normally use:
for i, v in pairs(Folder:GetChildren()) do
end
I seen some use _ instead of i, what difference does this make?
(ex)
for _, v in pairs(Folder:GetChildren()) do
end
And some I also see change v to a name (only know of using player)
(ex)
for _, player in pairs(game.Players:GetPlayers()) do
end
If Possible, does anyone mind explaining the last one for me, I don’t understand what changing v to players does (unless it just changes the name)
But what difference do these all make and which should be used over others
So for i, v in pairs() loops are declaring variables at the start.
I and v are variables. You are free to rename either to whatever you want. The first variable (often i) is just listing off either the index in an array or the key of a dictionary.
The v usually is the item and can also be freely renamed to reflect what it is like in your player example.
When people use _ in either place it usually just means they don’t actually need that variable.
So in your example
for _, player in pairs(game.Players:GetPlayers()) do
end
That means that the loop only needs to know the players that are children of game.Players. They don’t need what would normally be called i since usually you don’t need to care in which order the players come in.
You need to create 2 variables. The code knows what each variable means because of the order they are in. So you can name it whatever you want, but if you don’t intend to use one in your loop it’s best to do an underscore.
so just to iterate what others have said your free to use any name for variables you like
the job of these variables are to point to locations in memory where the value is stored
so
local i = 1234
is the same as
local hksdjhfksjhdfksjhdfkjshdf = 1234
we have just given it a different label for the location where this value is stored in memory
when you use for it will also use variables to store values and your free to use any label for these variables just like in the examples above
for i, player in ipairs(game.Players:GetPlayers()) do
print(i, player)
end
is the same as
for sdfhskdjhfskjdfhksjd, hskdja7a4sdhgfj7209 in ipairs(game.Players:GetPlayers()) do
print(sdfhskdjhfskjdfhksjd, hskdja7a4sdhgfj7209)
end
if your trying to read your old scripts or working with other scripters they wont be very happy when they try to work on code with variables called hskdja7a4sdhgfj7209 so its always best to use labels that help you or others understand whats going on
so instead of using hskdja7a4sdhgfj7209 it would be better to call the variable player so that its obvious that the location in memory points to the player instance
some people use _ for variables they are not using i personally do not do this
its personal taste so you need to ask your self if you want to use _ or if you don’t