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

[SOLVED]trouble with error handling

Started by CreeperGoBoom, 17 December 2018 - 07:32 PM
CreeperGoBoom #1
Posted 17 December 2018 - 08:32 PM
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 on 18 December 2018 - 12:59 PM
Lupus590 #2
Posted 17 December 2018 - 09:05 PM
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 on 17 December 2018 - 08:06 PM
Bomb Bloke #3
Posted 18 December 2018 - 02:50 AM
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

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.
CreeperGoBoom #4
Posted 18 December 2018 - 01:59 PM
[solved]

Thanks guys

@Bomb Bloke, Thanks for explaining the pcall function.