7.2. Macros

Macros are collections of assembler directives. When called, they generate code as if the directives where placed at the macro call. The following code defines and executes the macro ‘SetColor’:

// Define macro
.macro SetColor(color) {
    lda #color   
    sta $d020
}

// Execute macro
:SetColor(1)
SetColor(2)   // The colon in front of macro calls is optional from version 4.0  

A macro can have any number of arguments. Macro calls are encapsulated in a scope, hence any variable defined inside a macro can't be seen from the outside. This means that a series of macro calls to the same macro doesn't interfere:

// Execute macro
ClearScreen($0400,$20)   // Since they are encapsulated in a scope 
ClearScreen($4400,$20)   // the two resulting loop labels don’t
                          // interfere


// Define macro
.macro ClearScreen(screen,clearByte) {
    lda #clearByte
    ldx #0
Loop:         // The loop label can’t be seen from the outside
    sta screen,x
    sta screen+$100,x
    sta screen+$200,x
    sta screen+$300,x
    inx
    bne Loop
}

Notice that it is ok to use the macro before it is declared.

Macros in Kick Assembler are a little more flexible than ordinary macros. They can call other macros or even call themselves - Just make sure there is a condition to stop the recursion so you won't get an endless loop.