apemanzilla, on 15 March 2015 - 01:42 PM, said:
RoD, on 15 March 2015 - 10:58 AM, said:
apemanzilla, on 15 March 2015 - 03:48 AM, said:
RoD, on 14 March 2015 - 03:29 PM, said:
Tip: if you want to exit your program with an error (i also do this sometimes) At least create a error handler and if the error code is like "ok" or "exit" (anything you want, really) it will run a code block. For example:
function main()
print("Place in main() ALL of your code")
error("ok")
end
ok, err = pcall(main)
if not ok then --if the handler trows an error
if err == "ok" then --if the error is "ok" (error from the second line of the main function) then it will run the following code:
term.clear()
term.setCursorPos(1,1)
print("Thank you for using this program")
end
end
...What? That just defeats the purpose of pcall. Why use the error("ok") part at all? If it exits WITHOUT throwing an error, ok will be false, meaning that no error occurred, but if an error does occur, it will be true.
In the function "main" i called an error, wich will be "ok". When the pcall receives the error, it will check if the error name is "ok" ( at least i should use string.sub() to check only the 2 last characters of the error code). But if the error is "ok" it will run that code. And this was just an example, in more complex code its easier to exit the program this way.
EDIT: Ok i think i got what you are saying. If no parameter is given in the error function the program will exit right away.
What I was asking was, why add the "error('ok')" line? You can still detect if there wasn't an error without needing to call for and test for that.
For example:
function main()
--# Do stuff
end
local ok, error = pcall(main)
if ok then
term.clear()
term.setCursorPos(1,1)
print("Thank you for using this program")
else
--# Handle error
end
This code would do the exact same thing as yours.
That would print "thank you, etc" at the end of the program.
When i call error() is so i can exit the code whenever i want. For example:
function main()
print("hello")
sleep(1)
error("ok") --#if i call an error here i can stop the program exactly here, and no more code will be ran
print("testing")--#this code will not run because i exited the program at the error("ok")
sleep(1)
end
local ok, error = pcall(main)
if not ok and error == "ok" then
term.clear()
term.setCursorPos(1,1)
print("Thank you for using this program")
end
The idea of calling the error is to exit from the program from everywhere i want. Not only at the end of the program.