This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Early_Sep_99_Baby's profile picture

Add a set number of times to loop

Started by Early_Sep_99_Baby, 21 December 2012 - 09:34 AM
Early_Sep_99_Baby #1
Posted 21 December 2012 - 10:34 AM
I probably sound like such a noob, but is there a way to have a loop be repeated a set number of times. I know I could just type it out a bunch of times, but i want it to repeat the code 5 times, and honestly I don't have the patience to write out my code again and again. If there is any solution to my problem it would be greatly appreciated.
Thank you.
PixelToast #2
Posted 21 December 2012 - 10:36 AM
this belongs in ask a pro
use the for command:

for var=1,5 do
print(var)
end
that will output:

1
2
3
4
5
ChaddJackson12 #3
Posted 21 December 2012 - 07:32 PM
You can use something like a repeat loop, or even a while loop.

Repeat loop:

i = 8
repeat
 -- code
 i = i - 1
until i < 1

While loop:

i = 8
while not i == 0 do
 -- code
 i = i - 1
end

Both of those loops should work, and only loop 8 times. Hope I helped!
cmurtheepic #4
Posted 21 December 2012 - 07:38 PM
you could do

while I = 1, 1 do
-- then the loop
end
Orwell #5
Posted 21 December 2012 - 09:06 PM
you could do

while I = 1, 1 do
-- then the loop
end
I suppose you mean:

for I = 1, 1 do
-- then the loop
end
Which is the same as what PixelToast suggested.
remiX #6
Posted 21 December 2012 - 11:06 PM
To OP: The easiest would be to use the for loop, you can also go down in the loop and jump a specific times:

Decrementing:
for i = 15, 1, -1 do    -- The -1 makes the loop decrement by -1 each step
    print(i)
end
Output:
15, 14, 13, 12, ..., 3, 2, 1

Incrementing:
for i = 1, 20, 4 do    -- The 4 makes it jump 4 each time
    print(i)
end
Output:
1, 5, 9, 13, 17
ChunLing #7
Posted 22 December 2012 - 12:07 AM
I almost never use anything other than the standard increment behavior, if I want a multiple of the number of times the loop has actually executed I use i*m (m being my multiple and i being the for index/iteration/whatever). I do very occasionally use a decrement loop, those are pretty useful.

In other words, do what PixelToast says (only use for i=1,5 do, "i" is kinda a standard iteration identifier).
PixelToast #8
Posted 22 December 2012 - 03:47 AM
i usually use l1 and increase whenever i use a loop inside a loop
ChunLing #9
Posted 22 December 2012 - 12:28 PM
Yes, technically you can nest a loop and still use "i" as the identifier for the iterator value, but this prevents you from having access to the iterator values for the outer loops. And generally, if you're using nested loops, you'll want to be able to grab those. At least I pretty much always do.