Can anyone help me by explaining how those ^ sentences work and how I can use it in my codes and what they do and how they help.
Thanks, ConnorVIII.
Questions about for
loops have been asked a lot. Use the search feature to find lots of other questions and answers.
One of the first questions on SH
This is called a generic for
loop.
The general form is
for (some variables) in (some iterator) do
The loop repeatedly asks the iterator (usually pairs
, next
, ipairs
) for new values to fill in the variables you wrote (left of in
).
pairs(tab)
will repeatedly give us pairs of variables that enumerate all of the indices and values in the table tab
.
That is,
for index, value in pairs(tab) do print( tab[index], value ) end
Not only will tab[index]
and value
always be the same, this loop will visit every index
in the table.
Thus, if you have a list of things, you can do something involving each item in a list very briefly using a pairs
for
loop:
things = workspace:GetChildren() numberOfThings = #things for i, thing n pairs(things) do if thing:IsA("BasePart") then thing.Transparency = i / numberOfThings end end
ipairs
is very similar to pairs
. There are two differences:
ipairs
won't give you every index. It will only give the indices 1, 2, 3, ..., #tab
ipairs
will give you the above in order. pairs
can give you the indices in any order at all.Thus, when you have a list where the order matters, you should use ipairs
.
for i,v in ___, ___do is a loop that selects parts of a table or objects within workspace or anywhere else.
So for example:
for i, v in pairs (game.Workspace.Model) do --selecting objects within the Model in Workspace if v:IsA("Part") then -- If v (the parts inside the model) has a ClassName of Part then.. print(v.Name) -- we will print out the name of the part(s) end
Using the for i, v in pairs do loop is quite useful because you can select many parts that may have the same name and give them a certain property whether it may be setting all parts' Transparency to 1 or setting their Locked property to true. You can also use it to add things into objects whether it may be Smoke, Sparkles, or Explosions at the same time instead of copying and pasting for each part.
Hope this helps.
for i,v in pairs(table) do
i is the iteration number v is the table value
it's just like
a = game.Workspace:GetChildren() for i = 1, #a do
but instead of calling the child with a[i] which is the table position you can just use v