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

Struggling with turtle.inspect().

Started by Fiixii52, 31 May 2016 - 07:40 PM
Fiixii52 #1
Posted 31 May 2016 - 09:40 PM
Hello,

I've recently been trying to write my own quarry program : This will be the first big program I will ever write, so before I searched for some info about LUA. I know there's a ton of them in this forum, but I prefer making one myself … because why not \o/
I wrote a function that allows the turtle to compare the blocks above and below him by comparing the names of the blocks that are stored in a table (MiningSave) and the name of the blocks with turtle.inspectUp() and turtle.inspectDown().


function isJunkBlock(direction)
   local MaxTable = table.maxn(MiningSave)
   for i=8,MaxTable do
	   if direction == "up" then
			   local Success,Data = turtle.inspectUp()
	   elseif direction == "down" then
			   local Success,Data = turtle.inspectDown()
	   end
	   if Data.name == MiningSave[i] then
				 return true
	  end
   end
   return false
end

The problem is that whenever the program uses this function, I get an "attempt to index ? (a nil value)" error. Any help please ?

Fiixii52.
KingofGamesYami #2
Posted 01 June 2016 - 01:33 AM
The error "attempt to index ? (a nil value)" means you are treating a variable which is nil as a table.

Your specific problem is related to scope. Success and Data are not defined when you attempt to retrieve the name of the block.

Fix:

function isJunkBlock(direction)
   local MaxTable = table.maxn(MiningSave)
   for i=8,MaxTable do
           local Success, Data --#localize the variables to the loop
           if direction == "up" then
                           Success,Data = turtle.inspectUp() --#change the variables pre-defined above
           elseif direction == "down" then
                           Success,Data = turtle.inspectDown()  --#change the variables pre-defined above
           end
           if Data.name == MiningSave[i] then
                                 return true
          end
   end
   return false
end

And, just because I can (and have nothing better to do), I'll write it "my way"
Spoiler

function isJunkBlock( dir )
  for i = 8, #MiningSave do
    local success, data = turtle[ dir == "up" and "inspectUp" or "inspectDown" ]()
    if success and data.name == MiningSave[ i ] then
       return true
    end
  end
  return false
end