RPTools

From MapToolDoc

Custom Robust eval Function

 Note: This function can only be used in a Trusted Macro

This user defined function redefines the standard eval() function, allowing it to be given a number, empty string, or JSON object/array and not throw an exception.

Macros

Place both of these macros on the same library token.

1.3b56+


onCampaignLoad
  1. [ defineFunction( "eval", "evalFunction@this", 1, 0 ) ]



evalFunction
  1. //  Error handling
  2. [ assert( argCount() >= 1, "<b>eval()</b> - Invalid number of parameters <i>0</i>,
  3.                             expected at least <i>1</i> parameter.", 0 ) ]
  4.  
  5. //  Initialise variables
  6. [ X_Expression_X = arg( argCount()-1 ) ]
  7. [ X_CancelEval_X = 0 ]
  8. [ X_TypeTest_X = json.type( X_Expression_X ) ]
  9.  
  10. //  Handle all numbers
  11. [ if( isNumber( X_Expression_X ) == 1 ), code:
  12. {
  13.    [ X_CancelEval_X = 1 ]
  14. } ]
  15.  
  16. //  Handle empty strings
  17. [ if( X_TypeTest_X == "UNKNOWN" ), code:
  18. {
  19.     [ if( X_Expression_X == "" ), code:
  20.     {
  21.         [ X_CancelEval_X = 1 ]
  22.     } ]
  23. } ]
  24.  
  25. //  Handle JSON types
  26. [ if( X_TypeTest_X == "ARRAY" || X_TypeTest_X == "OBJECT" ), code:
  27. {
  28.     [ X_CancelEval_X = 1 ]
  29. } ]
  30.  
  31. //  Evaluate or cancel, then return
  32. [ if( X_CancelEval_X == 1 ), code:
  33. {
  34.     [ macro.return = X_Expression_X ]
  35. };{
  36.     [ macro.return = oldFunction( X_Expression_X ) ]
  37. } ]