The while and repeat loops
- A while loop and a repeat loop have three required parts
- A statement that initialize a loop variable
- A while or repeat condition that tests the loop variable eventually ending the loop
- A statement within the loop that changes the loop variable so that the loop eventually ends
- The while loop tests its conditon at its start and may never execute its body
- The repeat loop always executes once and tests its loop condition at its end
- The basic structure of the while is the following:
-- set up a loop variable -- while conditionTestingLoopVariable do -- body of the loop -- change the loop variable -- end -- an example of the while loop local i = 1 local a = {"Oak", "Pine", "Cherry", "Fir"} while a[i] do print (a[i]) i = i + 1 end
- The basic structure of the repeat loop is the following
- Note that in this case the loop always runs once
- Which in this case prints nil to the console
- a[5] is nil since it is beyond the initialized portion of the table
-- set up a loop variable -- repeat -- body of the loop -- change the loop variable -- until conditionTestingLoopVariable -- an example of the repeat loop local i = 5 local a = {"Oak", "Pine", "Cherry", "Fir"} repeat print (a[i]) i = i + 1 until a[i]