BETA mahshid.de is still being built โ€“ things may change or wobble.Still under construction. Feedback
DE
Lesson 5 of 11 ยท Scripting

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
end

while: 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)
end

Careful: 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?

What happens with while true do without task.wait?

๐Ÿค– Practise it in the code adventureLevel 6: Long way โ†’

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.