Skip to content

Constant Definitions

Bananattack edited this page Apr 21, 2011 · 10 revisions

The Language Reference - Constant Definitions

Constant definitions are used to bind a name to a constant expression. This can reduce on the amount of magic numbers appearing in code. These don't require any ROM space where they're defined, but are instead are substituted into whatever expressions that use them. This is accomplished by let name = expr, where name is what to call this constant, and expr is the value to bind to it.

The constant definition can optionally include a size, of either byte or word, to constraint the values a constant can take on. This gives an extended syntax of let name : size = expr. The constraint is evaluated when the constant's expression is evaluated, which isn't until it's referenced somewhere.

All constants by default have a size of word. However, if a constant is declared as word-sized but evaluates within the range 0..255, nel is still smart enough to take advantage of this when it matters.

Example

This is an example of some constant definitions:

let ppu_ctrl = 0x2000
let ppu_mask : word = 0x2001
let ppu_stat : word = 0x2002

let PLAYER_INITIAL_HP : byte = 10

def palette: begin
    let BACKGROUND : byte = 0x0F
    byte:
        // Tiles
        BACKGROUND, 0x10, 0x11, 0x30,
        BACKGROUND, 0x10, 0x11, 0x19,
        BACKGROUND, 0x0F, 0x0F, 0x0F,
        BACKGROUND, 0x0F, 0x0F, 0x0F,
        // Sprites
        BACKGROUND, 0x0F, 0x17, 0x37,
        BACKGROUND, 0x0F, 0x11, 0x21,
        BACKGROUND, 0x0F, 0x05, 0x05,
        BACKGROUND, 0x0F, 0x05, 0x05
end
Clone this wiki locally