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

HELP- Detecting for errors

Started by snakevenom, 22 December 2014 - 09:59 PM
snakevenom #1
Posted 22 December 2014 - 10:59 PM
Hello, recently I have found the need to detect if a certain piece of code will crash the program and therefore produce a error. I am familiar with other programming languages such as python which has try and except. These pieces of code detect if the code will cause a crash and if it does it runs the code in the except section.

Is there a way to replicate this in ComputerCraft? It would be incredibly useful.

Thank you.
theoriginalbit #2
Posted 22 December 2014 - 11:11 PM
Lua has the function pcall (PiL link) to catch errors, usage example

--[[
ok will be a boolean of running success
msg will either be the error message (if it failed) or the first return result from the function (if it succeeded).
we give it the function pointer, and any arguments it needs to be invoked with
--]]
local ok, msg = pcall(term.setCursorPos, 1, 1)
if not ok then
  print( msg ) --# print the reason it failed
end
since this can only do one instruction at a time I prefer to use the following model


local function main( tArgs )
  --# run program here, any uncaught errors will be caught by the main pcall below
end

local ok, err = pcall( main, { ... } )

if not ok and err:lower ~= "terminated" then --# if it failed, and wasn't a termination
  print( "The program had fatal error" )
  print( err )
end
Edited on 22 December 2014 - 10:11 PM