You may want a local macro to operate with a column, constant, or matrix-whatever the user decides to use when he or she invokes the macro. The local macro can then take appropriate action, depending on the type of variable used when invoking the macro. A free variable is an argument variable whose type-column, constant, or matrix-is not determined until the macro is invoked.
You must do five things in the local macro code to make free variables work:
1 List the free variable as an argument on the template. For example, here is a template for the macro TELLME that has X as an argument: TELLME X
2 Declare the free variable with the declaration statement MFREE. For example: MFREE X
3 Declare an additional variable as a constant: MCONSTANT Vartype
4 Use the macro statement MTYPE to analyze the free variable and store its variable type number in the constant declared in step . If the variable is a constant, then Vartype is set to 1; if it is a column, Vartype is set to 2; and if it is a matrix, Vartype is set to 3. You can include an MTYPE statement anywhere within the body of a local macro. For example, the command MTYPE X Vartype looks at the free variable X and stores its variable type (1, 2, or 3) in the constant Vartype.
5 Write code that can respond to the variable type that was used. In the following example, the IF statements make the macro perform different actions depending on what type of variable X is: IF Vartype = 1, NOTE X is a constant!, ELSEIF Vartype = 2, NOTE X is a column!, ELSE, NOTE X is a matrix!, ENDIF.
6 Invoke it. Macros that use free variables are invoked just like any other local macro (for details, see Invoking a Local Macro).
Note There is one case when the macro processor cannot determine the type of a variable. This happens when a variable that appears on an optional subcommand is declared as MFREE, and a user invokes the macro without using the subcommand. In this case, the macro processor assumes the variable is a column.
The local macro TELLME tells the user what kind of variable was used when the variable was invoked. Here is the complete code:
MACRO
TELLME X
MFREE X
MCONSTANT Vartype
MTYPE X Vartype
IF Vartype = 1
NOTE X is a constant!
ELSEIF Vartype = 2
NOTE X is a column!
ELSE
NOTE X is a matrix!
ENDIF
ENDMACRO
TELLME can be invoked in all of the following ways, and will produce the following output in the Session window:
Invoked like this |
Produces this |
%TELLME C1 |
X is a column! |
%TELLME K1 |
X is a constant! |
%TELLME M1 |
X is a matrix! |
Example of a more complex macro that uses free variables