Jump to content




Use pcall() to handle errors


  • You cannot reply to this topic
No replies to this topic

#1 Jummit

  • Members
  • 126 posts
  • LocationJulfander Squad Studio

Posted 05 October 2017 - 12:17 PM

Did you had the problem that the error line wasn't visible because of you're buffering?
Or did you want to write the error of a program in a log file?


You can easily do this by using the pcall() function.
Here is my simple program from which i want to to log the errors from.
buffer = window.create(term.current(), 1, 1, term.getSize())
local oldterm = term.redirect(buffer)

buffer.setVisible(false)
error("test")
buffer.setVisible(true)
You see the 'error("test")'? Normally it would show a red error on the terminal. But we redirected the terminal to a buffer which doesn't get drawn because we set it invisible. So we will never see the error.

How we can use the pcall function to write the error(if there is one) on the screen:
buffer = window.create(term.current(), 1, 1, term.getSize())
local oldterm = term.redirect(buffer)
function main()
  buffer.setVisible(false)
  error("test")
  buffer.setVisible(true)
end

no_error, message = pcall(main)
term.redirect(oldterm)
shell.run("clear")
if not no_error then
  print(message)
end
The pcall function needs a function. It runs it and returns if it was successful or not and the error if there was one.
So we create a function main, which holds our program and run pcall with main as argument.
Now we get no_error, a variable which is false if the program failed and true if there was no error and message, which is the error.
Now we only need to check if there is an error, and if it is so, we print it. You can of course do what you want with the error, write it to a file or make a nice UI and print it on the crash.

Hope you found this helpful and learned something!

Further reading:
Lua documentation of pcall and more: https://www.lua.org/....html#pdf-pcall
Buffering with Computercraft if you don't know how it works: http://www.computerc...ki/Window_(API)

Edited by Jummit, 05 October 2017 - 12:25 PM.






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users