Page 1 of 1

Workaround for macro functions

Posted: Sat Jun 27, 2009 8:00 am
by Mistrel
I needed macro functions to greatly simplify error handling in one of my projects. I also made a feature request about it here:

http://www.purebasic.fr/english/viewtopic.php?t=37568

I did some brainstorming today and managed to find a workaround to get similar functionality of macro functions. The only difference is that it passes the result of the value/expression to a function which is typed. So it's not a "true" macro but it's perfect for integer results and other common types. It doesn't work for expressions so I've included a second macro If_ErrorHandler() to work around that as well.

Code: Select all

#ERR_SUCCESS=0
#ERR_CUSTOM=-1

Procedure _CopyResultInteger(Input, *Output.Integer)
  If *Output
    *Output\i=Input
  EndIf
  ProcedureReturn Input
EndProcedure

;/ Exit thread on negative return values
Macro ErrorHandler(Expression)
  _CopyResultInteger(Expression,@ExpressionResult): If ExpressionResult<0: ProcedureReturn ExpressionResult: EndIf
EndMacro
Macro If_ErrorHandler(Expression)
  _CopyResultInteger(Expression,@ExpressionResult): If ExpressionResult<0: ProcedureReturn ExpressionResult: EndIf: If ExpressionResult
EndMacro

Procedure SomeFunctonSuccess()
  ProcedureReturn #ERR_SUCCESS ;/ Success
EndProcedure

Procedure SomeFunctonError()
  ProcedureReturn #ERR_CUSTOM ;/ Some error
EndProcedure

Procedure Thread()
  n=ErrorHandler(SomeFunctonSuccess())
  ;/ Comparison operator must always compare from left to right
  If_ErrorHandler(SomeFunctonSuccess())=#ERR_SUCCESS
    Debug "#ERROR_SUCCESS"
  EndIf
  n=ErrorHandler(SomeFunctonError())
  Debug "This is never printed because the macro exits the procedure early"
  ProcedureReturn #ERR_SUCCESS
EndProcedure

If Thread()=#ERR_CUSTOM
  Debug "#ERROR_CUSTOM"
EndIf