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

I cannot find the typo :(

Started by Exitialis, 22 June 2015 - 09:41 PM
Exitialis #1
Posted 22 June 2015 - 11:41 PM
Hey,

I don't want to know how many times I have stared at this code and I suspect that I am missing something really obvious but I cannot for the life of me work out what it is. It gives the attempt to index a nil value error for the line "if not string.match(Item.name,"coal") then".


print("Current fuel level: ", turtle.getFuelLevel())
function CheckFuel()
    if turtle.getFuelLevel() <= 100 then
  turtle.refuel(1)
  print ("Turtle refuelled by 1")
  print("Turtle fuel level: ", turtle.getFuelLevel())
    end
end
function Dump()
for k=1,16 do
  local Item = turtle.getItemDetail(k)
  if not string.match(Item.name,"coal") then
   turtle.select(k)
   turtle.drop()
   print("Dropping: ",Item.name)
  end
end
end
function Dig()
if turtle.detect() then
  turtle.dig()
end
local i = 0
while turtle.detectUp() do
  turtle.digUp()
  i = i+1
end
while i < 0 do
  turtle.down()
  i = i-1
end
end
function ScanRow()
for i=1,10 do
  Dump()
  Dig()
  turtle.forward()
end
end
for j=1,10,2 do
CheckFuel()
ScanRow()
print("j = ", j)
turtle.turnRight()
if not turtle.forward() then
  Dig()
  turtle.forward()
end
turtle.turnRight()
CheckFuel()
ScanRow()
print("j = ", j+1)
turtle.turnLeft()
if not turtle.forward() then
  Dig()
  turtle.forward()
end
turtle.turnLeft()
end

If anyone could help me find the incorrect part I'd be very grateful.
Bomb Bloke #2
Posted 22 June 2015 - 11:51 PM
turtle.getItemDetail() either returns a table containing info about the contents of the selected slot, or, if nothing was in that slot, it returns nil. You need to check whether anything was found before you attempt to index into "Item" to get "name".

Eg:

if Item and not string.match(Item.name,"coal") then  -- If slot contained an object, and the object's name doesn't contain "coal", then...

Lua's bright enough to realise that if "Item" is nil then the above statement will resolve to false no matter what String.match returns, so it doesn't perform the call and won't error out.
Edited on 22 June 2015 - 09:53 PM