Macros

A macro is a piece of source text with a name. Wherever the name is used, the compiler substitutes the text before compiling it. Macros cost nothing when the program runs.

Defining a macro ✅

Macro Square(x)
  ((x) * (x))
EndMacro

OpenConsole()
PrintN(Str(Square(7)) + " " + Str(Square(1 + 2)))

Output:

49 9

Arguments are substituted as written, so Square(1 + 2) becomes ((1 + 2) * (1 + 2)). That is why the body puts brackets around each x: without them, x * x would become 1 + 2 * 1 + 2, which is 5.

A macro must be defined before it is used.

Several statements

A macro body can hold whole statements:

Macro Log(text)
  PrintN("[log] " + text)
EndMacro

OpenConsole()
Log("starting")
For i = 1 To 2
  Log("pass " + Str(i))
Next

Output:

[log] starting
[log] pass 1
[log] pass 2

No brackets

A macro defined without brackets replaces its name wherever it appears:

Macro Greeting
  "Hello from a macro"
EndMacro

OpenConsole()
PrintN(Greeting)

Output:

Hello from a macro

Default arguments

A parameter can have a default, used when the argument is left out:

Macro Triple(text, sep = ", ")
  text + sep + text + sep + text
EndMacro

OpenConsole()
PrintN(Triple("a"))
PrintN(Triple("b", "-"))

Output:

a, a, a
b-b-b

Joining names with #

Inside a macro, # directly between two parts (no spaces) joins them into one name. This makes macros that define things:

Macro Counter(name)
  Global name#_count
  Procedure name#_bump()
    name#_count + 1
  EndProcedure
EndMacro

Counter(apples)
Counter(pears)

OpenConsole()
apples_bump()
apples_bump()
pears_bump()
PrintN(Str(apples_count) + " " + Str(pears_count))

Output:

2 1

UndefineMacro ✅

UndefineMacro Name removes a macro, so the name can be defined again:

Macro Label
  "first"
EndMacro

OpenConsole()
PrintN(Label)
UndefineMacro Label

Macro Label
  "second"
EndMacro
PrintN(Label)

Output:

first
second

Things to know

  • Macros work on the program's text, not its values. Each use of a parameter repeats the argument's text, so an argument with a side effect, such as a procedure call, runs once per use.
  • Errors in the substituted text are reported at the line where the macro is used.
  • A macro that uses itself can't be expanded completely. The compiler reports it instead of hanging.
  • Macros are visible from their definition to the end of the program, across included files.

Not yet available 🔜

  • MacroExpandedCount.
  • C-style #define.