defer test
Posted: Wed Sep 11, 2024 5:43 pm
Found this defer macro and played around a little bit. It's very restricted (in PB), cumbersome and verbose (.c file), but somehow works...
Code: Select all
CompilerIf #PB_Compiler_Backend <> #PB_Backend_C
CompilerError "'defer test' needs the C backend (GCC only)"
CompilerEndIf
Macro defer_Pb(func)
! #undef CAT_
! #undef CAT
! #undef defer
! #define CAT_(a, b) a ## b
! #define CAT(a, b) CAT_(a, b)
! #define defer \
! auto void CAT(DEFER_FUNCTION_, __LINE__)(int *); \
! int CAT(DEFER_VAR_, __LINE__) __attribute__((cleanup(CAT(DEFER_FUNCTION_, __LINE__)))); \
! void CAT(DEFER_FUNCTION_, __LINE__)(int *)
! defer { PB_#func; }
EndMacro
Macro defer_My(func)
! #undef CAT_
! #undef CAT
! #undef defer
! #define CAT_(a, b) a ## b
! #define CAT(a, b) CAT_(a, b)
! #define defer \
! auto void CAT(DEFER_FUNCTION_, __LINE__)(int *); \
! int CAT(DEFER_VAR_, __LINE__) __attribute__((cleanup(CAT(DEFER_FUNCTION_, __LINE__)))); \
! void CAT(DEFER_FUNCTION_, __LINE__)(int *)
! defer { f_#func; }
EndMacro
Procedure My_Print(txt$)
PrintN(txt$)
EndProcedure
Procedure Run()
defer_Pb(PrintN(L"\npress any key to continue...")) ;;; L"" needed to output wide-character strings
My_Print(~"defer test:\n") ;;; if ommited, calling next line: defer_My(my_print(..)) = unresolved external symbol
defer_My(my_print(L"\nexpected output: 1, 3, 4, 6, 5, 2")) ;;; my_print must be lower case...
PrintN(" 1 ")
defer_Pb(PrintN(L" 2 "))
PrintN(" 3 ")
PrintN(" 4 ")
defer_Pb(PrintN(L" 5 "))
PrintN(" 6 ")
EndProcedure
OpenConsole()
defer_My(my_print(L"not working in PB's main scope"))
Run()
Input()