Jump to content

[Beginner] select+pcall to catch full error messages


rain_gloom

Recommended Posts

Since MTA does not always report the full error message, you are better off using this little trick, whenever you aren't sure what's wrong.

Here is a very simple script we want to debug:

error"I'm an error!" 

(I couldn't find a better example. This gives a proper message, but more complex errors sometimes don't. If you can find a better error, please share.)

Here is the same thing wrapped inside a pcall.

outputDebugString(select(2,pcall(function() 
  
error"I'm an error!" 
  
end)) or "Everything went smooth.") 

Here is what happens:

We wrap the script into a function. This changes nothing in its behaviour. (except that it won't automatically run if we don't call it, but we will take care of that.)

We call the new function using 'pcall'. 'Pcall' is a very useful function, which executes a function, then returns 'true' (and whatever the function returned) if it ran without errors and 'false' and the error message if it failed.

We want to get that error message printed, so we use 'select'. This is a vararg function. Its first argument indicates how many of the following arguments should be discarded. Example:

print(select(2,1,2,3)) 

Will print:

2,3 

We use that to select the returned error message, which is then printed, but only if it exists.

Since MTA scripts rarely return anything at the end of the file (which is used in normal Lua to create modules), if there was no error, then 'pcall' only return 'true'. Hence the second argument is 'nil'.

We can leave it nil, we'll only get a warning that 'outputDebugString' was expecting a string, but let's make it a bit more correct with this simple trick.

As you should already know, 'or' does not necessarily return a boolean, it returns whichever operand was not 'false' or 'nil'.

If the first operand evaluates to false (only 'false' and 'nil' does) it returns the second one, in this case, the message telling us that everything went smooth.

I hope I could help, writing this sure passed some time on networking class. :mrgreen:

Note:

this won't automatically work for functions called by event handlers, but the principle is the same

Link to comment
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...