Eliot’s Tips and Tricks

Different, simple and elegant.

The error call can be used to explicitly raise an error and will stop a script. If instead you wish to catch the error then use the pcall function to call a Lua function in protected mode. This means you can check the first argument returned to see if the function ran without error, true or false. If an error occurred the second argument returned is the error message.

So it means your scripts can skip past a message that creates an error or perform any other kind of error handling you choose to do. This code demonstrates the use of pcall

The function you want to call is passed as the first parameter, followed by the parameters to the function. pcall() will return false if an exception is thrown.

If we comment out the error message:

Note: The main() function uses print() to log messages. When an Iguana channel is run print() messages are logged as informational messages. If you do not wish to log messages you should use a trace() function. For more sophisticated logging you can use the iguana.logInfo(), iguana.logWarning(), iguana.logDebug() functions.

The format of the error string can be a little tricky to break apart. If you have questions about this please contact support at support@interfaceware.com. Also have a look at this example.

One slight inconvenience with pcall is that it will suppress the Translator’s helpful error catching mechanism. A helpful technique for dealing with that is to do this:

Here’s the code:

function main(Data)
   local Success, Err = pcall(ProtectedMain, "DataIn")
   if not Success then
      print("Skipping error: "..Err)
   end
end

function ProtectedMain(Data)
   error("Bang!")
   return "Some", "Data"
end

Here’s the code with isTest() added:

function main(Data)
   if iguana.isTest() then
      -- We're in test mode so we won't use pcall
      ProtectedMain("DataIn")
   else
      local Success, Err = pcall(ProtectedMain, "DataIn")
      if not Success then
         print("Skipping error: "..Err)
      end
   end
end

function ProtectedMain(Data)
   error("Bang!")
   return "Some", "Data"
end
Tagged: