Loops: for and while
In the code adventure you used ๐ Repeat. In Luau that is a for loop โ and with while something runs as long as a condition is true.
What youโll learn
- repeat something exactly n times with for
- do something again and again with while
- add pauses with task.wait
for: exactly n times
The number i counts from 1 to 10. Here a part becomes invisible step by step:
local part = workspace.MyPart
for i = 1, 10 do
part.Transparency = i / 10
task.wait(0.1) -- wait 0.1 seconds
endwhile: again and again
A while true do loop runs forever โ for example for a part that changes colour every second:
local part = workspace.MyPart
while true do
part.BrickColor = BrickColor.random()
task.wait(1)
endCareful: never without task.wait
An endless loop without task.wait freezes Studio because it never pauses. Remember โtoo many stepsโ in the code adventure? That is exactly what happens here.
๐ ๏ธ Try it
Make a part grow slowly with a for loop (Size = Vector3.new(i, 1, i)). Then: a disco platform with while.
๐ง Mini quiz
How often does the body of for i = 1, 5 do โฆ end run?
i takes the values 1, 2, 3, 4, 5 โ five runs.
What happens with while true do without task.wait?
The loop never pauses and blocks everything else.
โ Lesson done! On to the next one.
Roblox and Roblox Studio are trademarks of the Roblox Corporation. mahshid.de is not affiliated with Roblox. All links to Roblox lead to the official sites.