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

for loops variable limit

Started by kxrider85, 20 November 2014 - 01:21 AM
kxrider85 #1
Posted 20 November 2014 - 02:21 AM
Hello everyone. This is my first post and I'm kinda new to computercraft. Anyway, I was making a loop like this:

term.write("how many times?: ")
local input = read()
for i=1, input do
  ........
  ...........
  .........
  .........
  i = i+1
end
After I type in my value. I get an error saying the limit must be a number, which it is. I also tried doing: for i=1, tonumber(input) do after seeing someone else doing that but it didn't work either. Please help! Thanks for any replies in advance.
Lyqyd #2
Posted 20 November 2014 - 02:35 AM
The tonumber() one should have worked, what'd you input for the limit? You don't need to increment the number in the for loop, the loop does that automatically for you.
Dragon53535 #3
Posted 20 November 2014 - 04:33 AM
To elaborate on Lyqyd's answer, a for loop is structured in this way

for starting number, ending number, [increment] do
Now i know you already know this and have set yours up this way, however read() always returns a string, even if you inputted a number. So if you inputted 10 your for loop looks like this.

for i=1, "10" do
That wouldn't work. Which is why you need tonumber() which converts a string into a number.

for i=1,tonumber(input) do

--#Makes it this

for i=1,10 do --#If you still inputted 10
If you notice, now 10 is a number, and it should work correctly.
However since you say that you tried tonumber, can you post your code with it?


Oh, and your for loop does automatically increment your counter variable.

for i = 1, 10 do --# The first time it runs

end

for i = 2, 10 do --#Second time

end

for i = 3, 10 do --#Third time and so on...

end
Lyqyd #4
Posted 20 November 2014 - 05:02 AM
That's really not a good way to demonstrate the automatic incrementing. It's kind of confusing if you're not already familiar with the concept.
kxrider85 #5
Posted 20 November 2014 - 11:27 PM
Thank you guys! I have it figured out now.