←  Ask a Pro

ComputerCraft | Programmable Computers for Minecraft

»

[SOLVED]trouble with error handling

CreeperGoBoom's Photo CreeperGoBoom 17 Dec 2018

so i have this code

local ingredients = {"cobblestone"}
local results = {}

local furn = peripheral.wrap("furnace_0")


  for i,v in pairs(furn.getStackInSlot(3)) do
	results[i]=v
  end
  if results["qty"] > 0 then
	print("output found")
  else
	print("Error: no output found")
  end

This is for a computercraft controlled auto furnace while I get the hang of using tables.

The problem i'm running into is that it keeps throwing an error when the output slot of the furnace is empty, works good so long as the output has something

THis is what happens when the output is empty:
 <program name>:7: bad argument, table expected, got nil.

the following code just seems to throw my custom error regardless.

local ingredients = {"cobblestone"}
local results = {}

local furn = peripheral.wrap("furnace_0")

if pcall(furn.getStackInSlot(3)) then
  for i,v in pairs(furn.getStackInSlot(3)) do
	results[i]=v
  end
  if results["qty"] > 0 then
	print("output found")
  end
else
	print("Error: no output found")
end

What am i missing?
Edited by CreeperGoBoom, 18 December 2018 - 01:59 PM.
Quote

Lupus590's Photo Lupus590 17 Dec 2018

try this
local ingredients = {"cobblestone"}
local results = {}

local furn = peripheral.wrap("furnace_0")

local itemInSlotThree = furn.getStackInSlot(3)

if itemInSlotThree and type(itemInSlotThree) == "table" then
  for i,v in pairs() do
	    results[i]=v
  end
  if results["qty"] > 0 then
        print("output found")
  else
        print("Error: no output found")
  end
end

Edited by Lupus590, 17 December 2018 - 09:06 PM.
Quote

Bomb Bloke's Photo Bomb Bloke 18 Dec 2018

View PostCreeperGoBoom, on 17 December 2018 - 08:32 PM, said:

THis is what happens when the output is empty:
 <program name>:7: bad argument, table expected, got nil.

getStackInSlot returns a table if something's in the specified slot, or nil if there's not. You're trying to pass the output to pairs without checking which type of value you got, hence the crash when nothing's there.

In a comparison statement, pretty much all data types count as true except for false and nil. You can hence do stuff like this to check whether you got a nil return value:

if furn.getStackInSlot(3) then
  print("Something's in the slot.")
else
  print("Nothing's in the slot.")
end

View PostCreeperGoBoom, on 17 December 2018 - 08:32 PM, said:

the following code just seems to throw my custom error regardless.

pcall expects to be passed a function, followed by any parameters you want it to pass to that function when executing it for you. Eg:

pcall(furn.getStackInSlot, 3)

You're calling the function and then passing its output to pcall.
Quote

CreeperGoBoom's Photo CreeperGoBoom 18 Dec 2018

[solved]

Thanks guys

@Bomb Bloke, Thanks for explaining the pcall function.
Quote