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

Error: attempt to perform arithmetic __add on number and nil

Started by Theagle43, 22 June 2013 - 10:37 PM
Theagle43 #1
Posted 23 June 2013 - 12:37 AM
I'm following a tutorial video that is teaching me to write a simple(ish) program to have the turtle move forward three blocks, then record its location. It is very much a WIP, I just want to know what the problem is. It is on the 28th line of this code:


xCoord = -479
zCoord = -20
yCoord = 66

orientation = 4
orientations = {"north", "east", "south", "west"}

local zDiff = {-1, 0, 1, 0}
local xDiff = {0, 1, 0 -1}

function left()
  orientation = orientation - 1
  orientation = (orientation - 1) % 4
  orientation = orientation + 1

  turtle.turnLeft()
end

function right()
  orientation = orientation - 1
  orientation = (orientation + 1) % 4
  orientation = orientation + 1

  turtle.turnRight()
end

function moveForward()
  xCoord = xCoord + xDiff[orientation] -- <--- This line
  zCoord = zCoord + zDiff[orientation]

  turtle.forward()
end

for i = 1,3 do
  moveForward()
  print("X: "..xCoord.." Z: "..zCoord)
end
Edited by
Lyqyd #2
Posted 23 June 2013 - 08:52 PM
Split into new topic.
johnnic #3
Posted 23 June 2013 - 11:20 PM
You are possibly getting a number that is not 1-4 with %.
lucassouza1996 #4
Posted 23 June 2013 - 11:42 PM
You forgot a comma right in the 'local xDiff' between the '0' and the '-1'!

One tip:

In the forward() function, don't only put the turtle.forward() because if you put just that and there is a monster on the way it will 'think' that went forward but don't, so change that function to this:


function forward()
xCoord = xCoord + xDiff[orientation]
zCoord = zCoord + zDiff[orientation]
turtle.dig()
forw = false
  while not(forw) do
   forw = turtle.forward()
  end
end

EDIT 1: Only put the turtle.dig() if you think that will be a block on the way, if monster put turtle.attack() or both!
Theagle43 #5
Posted 24 June 2013 - 12:37 AM
You forgot a comma right in the 'local xDiff' between the '0' and the '-1'!

Thank you so much!!! Ugh stupid, silly mistake!
theoriginalbit #6
Posted 24 June 2013 - 06:32 AM
Also just a note, with your code where you do this



orientation = orientation - 1
orientation = (orientation + 1) % 4
orientation = orientation + 1

If you wanted to refine it down a little to just have this


orientation = (orientation - 1) % 4

you could do that if you define your table like this


orientations = {[0] = "north", "east", "south", "west"}

now the indexes start at 0, not 1