Do something else with FOR

Hello, so I’m a beginner in scripting and I understood that FOR could be a loop, but except loops, can we do anything else with FOR?

Thanks.

1 Like

This isn’t exactly related to your question, but is FOR?

For allows you to loop through items. For example you could loop through a models parts via:

for _,v in pairs(workspace.Model:GetChildren()) do
     print(v) -- The part it looped through
end

You could loop through a table!

local t = {"Hello",1,true,"A","0"}
for _,v in ipairs(t)
     print(v) -- Will print the value it is currently looping through
end

A good use case could be if you were trying to make all parts within a model transparent you could loop through all the parts of the model and set them to transparent without having to write a line for each part

Something else to add to this is that for can be used as an incremental/decremental loop,

Examples

for i = 1, 10 do
	print(i)
end

-- Prints 1 2 3 4 5 6 7 8 9 10

You can also pass in a 3rd parameter which determines how you increase or decrease the variable

for i = 10, 1, -1 do
	print(i)
end

-- Prints 10 9 8 7 6 5 4 3 2 1
2 Likes

Thank you very much for the information.

1 Like

Thank you very much for the information provided.

1 Like