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

Need help with this program ('for' limit must be a number)

Started by RaRamonster, 07 November 2013 - 09:45 AM
RaRamonster #1
Posted 07 November 2013 - 10:45 AM
Title: Need help with this program

hey,

I want to have a turtle with mines a 3x3 area with a length given by me, i've come this var:

local a = { … }
if #a ~= 0
then
for i=1, a, 1 do
turtle.dig()
turtle.forward()
end
else
print("have to fill in a number")
end

i've saved the program to dig
when i run dig 2 it says "dig:4: 'for' limit must be a number"

who can help me?
Bubba #2
Posted 07 November 2013 - 11:03 AM
You are attempting to use the table 'a' as a number. If you want to get the value of the input as the number of times the turtle repeats the for loop, you need to do the for loop like this instead:

for i=1, tonumber(a[1]) do
  ...
end

This will get the value at index 1 of the table a and convert it to a number using tonumber.
Edited on 07 November 2013 - 10:03 AM
Engineer #3
Posted 07 November 2013 - 11:15 AM
I want to point you of a danger using Bubba's method. Sure, it cannot be done on another way, but what if the user types in: "ac". In this case you have the same problem again, so you want to make sure that the variable is capable of becoming a number.

We actually cannot check that, but we can check if the convert is succesful:

if tonumber( a[1] ) then
  print( "The first argument can be converted to a number!" )
end

So in this case you want to add that check:

if tonumber(a[1]) then
   for i = 1, tonumber(a[1]) do
     print("looping " .. i )
   end
end

Now we are calling the tonumber function twice, but really we only need one:

a[1] = tonumber( a[1] )
if a[1] then
   for i = 1, a[1] do
     print( "Looping " .. i )
   end
end
So as you can see we reassign the index 1 in the a table. Then we check if a[1] still exists. It gets garbagecollected when the tonumber function returns nil. But if it doesnt return nil, it will return the number!
Edited on 07 November 2013 - 10:16 AM
RaRamonster #4
Posted 07 November 2013 - 12:35 PM
so which thing do i have to fill in my program?
thanx for your help sofar