Page 1 of 1

Assert() macro

Posted: Tue Jun 16, 2009 9:47 pm
by Trond

Code: Select all

#Assert = 1

Macro QUOTE
  "
EndMacro

Macro Assert(Expression)
  CompilerIf #Assert
    If Not (Expression)
      MessageRequester("Program Error", "Assert failed at in file '" + #PB_Compiler_File + "' at line " + Str(#PB_Compiler_Line) + "." + #CRLF$ + "Assert: " + QUOTE Expression QUOTE)
      CallDebugger
      End
    EndIf
  CompilerEndIf
EndMacro

Assert(Apple = Orange)
#Assert = 1 enables asserts. To not compile the program with asserts, use #Assert = 0. Then you will have no speed penalty compared to a normal program.

Posted: Tue Jun 16, 2009 10:10 pm
by Octopus
Because of problems e.g. with comparing operators inside of expressions would it not be better e.g. to use:

Code: Select all

If Not (Expression)
instead of:

Code: Select all

If (Expression) = 0
or will the latter work anyway?

Posted: Wed Jun 17, 2009 9:48 am
by Trond
No, you are right.

Posted: Thu Jun 18, 2009 7:16 am
by Rescator
Here's a variant of Trond's most excellent Assert.

It's piggybacking fully on the Debugger, so if you compile without the debugger then assert is not compiled either.
Likewise, if an assert failure happen it will use the debug output instead of a requester.
And I removed the End, thus allowing you to choose Continue or Kill from the debug menu instead. (assuming you don't have auto kill enabled that is).

Would be cool if this was available as part of the debugger, but this way rocks too, I may actually find a use for this ;)

Code: Select all

Macro QUOTE
  "
EndMacro

Macro Assert(Expression)
 CompilerIf #PB_Compiler_Debugger
  If Not (Expression)
   Debug "Assert: "+QUOTE Expression QUOTE
   Debug "Line "+Str(#PB_Compiler_Line)+" in "+#PB_Compiler_File
   CallDebugger
  EndIf
 CompilerEndIf
EndMacro

Apple=1
Orange=2

Assert(Apple = Orange)