Cookbook & Tricks

Overview

This page collects common NCL programming patterns, useful idioms, and techniques that combine several instructions.

For the complete behavior of individual instructions, see the corresponding NCL or peripheral reference page.


Style Recommendations

Use Labels for Meaningful Destinations

Prefer labels for meaningful program locations. Use relative references when the relationship between nearby lines is itself useful.

BEQ :done $000 0

-- Work...

:done
HALT

Give Important Locations Names

Constants can give meaningful names to long-lived memory locations:

#score $000
#lives $001
#name  $002

MOVE #score 100
MOVE #lives 3
S.MOVE #name "Player"

Temporary locations generally do not need names.

Keep Destructive Operations Obvious

Many instructions allow the destination to also be a source:

ADD $000 $000 1
S.JOIN $001 $001 "!"

Use this freely when the original value is no longer needed.


Branching Patterns

Common higher-level control structures can be constructed directly from branches:

-- IF / ELSE
-- if $000 >= 100

BLT :else $000 100
D.TXT "HIGH"
JUMP :done

:else
D.TXT "LOW"

:done


-- AND
-- if $000 >= 10 AND $000 <= 20

BLT :outside $000 10
BGT :outside $000 20

D.TXT "INSIDE"
JUMP :andDone

:outside
D.TXT "OUTSIDE"

:andDone


-- OR
-- if $000 == 1 OR $000 == 3 OR $000 == 5

BEQ :match $000 1
BEQ :match $000 3
BEQ :match $000 5

D.TXT "NO MATCH"
JUMP :orDone

:match
D.TXT "MATCH"

:orDone


-- MULTI-WAY

BEQ :red   $000 1
BEQ :green $000 2
BEQ :blue  $000 3
JUMP :other

:red
D.TXT "RED"
JUMP :multiDone

:green
D.TXT "GREEN"
JUMP :multiDone

:blue
D.TXT "BLUE"
JUMP :multiDone

:other
D.TXT "OTHER"

:multiDone

For AND, branch away as soon as one condition fails. For OR, branch to a shared destination as soon as one succeeds.

Constructing a Boolean Value

Conditional branches do not store their result. When a comparison needs to become a value, construct 0 or 1 explicitly:

#score $001

BLT :below #score 100
MOVE $000 #TRUE
JUMP :done

:below
MOVE $000 #FALSE

:done
-- > $000 = 1 if #score >= 100, otherwise 0

A normalized boolean can be toggled with:

XOR $000 $000 1

Loop Patterns

Counted, sentinel, and infinite loops all use the same basic backward-branch pattern:

-- COUNTED LOOP

MOVE $000 10

:counted
D.TXT "Hello!\n"

DEC $000
BNEQ :counted $000 0


-- SENTINEL LOOP

:input
SYS.AKEY $000
S.BEQ :inputDone $000 "Q"

-- Process $000 here.

JUMP :input

:inputDone


-- INFINITE LOOP

:forever

-- Work...

JUMP :forever

If a counted loop may begin at zero or below, test the counter before entering it.


Stack Patterns

The data stack occupies ordinary memory and grows downward from sp.

Preserve and Restore Values

Values are restored in reverse order:

PUSH $000
PUSH $001

-- Use the locations temporarily.

POP $001
POP $000

Use the matching typed stack operation when the representation must be preserved:

PUSH $000
S.PUSH $001
F.PUSH $002

F.POP $002
S.POP $001
POP $000

Peek at the Stack

[sp] refers to the current top of the data stack without removing it:

PUSH 42

MOVE $000 [sp]
-- > $000 = 42
-- > 42 is still on the stack

POP $001

Because stack storage is ordinary RAM, [sp] may be used anywhere an indirect memory reference is accepted.


Program Flow

Leaving and Returning to a Program

SYS.NEXT and SYS.RUN can be combined to transfer execution to another program and later start a new invocation of the original program:

D.TXT "Leaving...\n"

SYS.NEXT #THIS :return "Welcome back!"
SYS.RUN "A:/OTHER.NCL" 0

:return
D.TXT #0

The returning program is a new invocation. CPU state from the previous invocation is not preserved; pass required state as arguments or store it elsewhere.

Returning to the Next Line

A relative entrypoint avoids needing a named return label:

SYS.NEXT #THIS @2 "Welcome back!"
SYS.RUN "A:/OTHER.NCL" 0

D.TXT #0

@2 is resolved to an absolute program line during the pre-pass before the current invocation begins executing.


Hardware Detection

Optional Peripheral Support

Use SYS.HW when a program can make optional use of a peripheral interface:

SYS.HW $000 "D"
BEQ :headless $000 0

D.TXT "Display available."
D.BLT

:headless

This tests for the interface namespace rather than a particular physical implementation of the peripheral.

Multiple optional interfaces can be tested independently:

SYS.HW $000 "D"
SYS.HW $001 "PRINT"
SYS.HW $002 "NET"

Random Numbers

Rolling Dice

RNG uses an exclusive bound beginning at zero. Add one per die to obtain conventional die values:

-- 1d6
RNG $000 6
INC $000
-- > 1–6


-- 1d20
RNG $000 20
INC $000
-- > 1–20


-- 2d6
RNG $000 6
RNG $001 6
ADD $000 $000 $001
ADD $000 $000 2
-- > 2–12

Roll 4d6, Drop the Lowest

The zero-based rolls can be summed directly, with the conventional +1 applied only to the three dice that remain:

RNG $000 6
RNG $001 6
RNG $002 6
RNG $003 6

-- Find the lowest.
MIN $004 $000 $001
MIN $004 $004 $002
MIN $004 $004 $003

-- Sum all four.
ADD $005 $000 $001
ADD $005 $005 $002
ADD $005 $005 $003

-- Drop the lowest.
SUB $005 $005 $004

-- Convert the three remaining 0–5 rolls to 1–6.
ADD $005 $005 3
-- > $005 = 3–18

Reproducible Random Sequences

A fixed non-zero seed reproduces the same PRNG sequence:

SEED 12345

PRNG $000 100
PRNG $001 100
PRNG $002 100

This is useful for procedural generation, repeatable simulations, and tests.

Use SEED 0 when a new random PRNG state is wanted instead.


Memory Tricks

Interpret the Same Value Differently

Memory has no stored type. The instruction consuming a value determines how it is interpreted:

S.MOVE $000 "42"

MOVE $001 $000
-- > $001 = "42"

S.JOIN $002 "Score: " $000
-- > $002 = "Score: 42"

A location does not need to be copied into a different kind of register before another operation family can use it.

Normalize a Numeric String In Place

Integer MOVE interprets its source as an integer and writes the resulting integer representation:

S.MOVE $000 "0xFF"

MOVE $000 $000
-- > $000 = "255"

The same pattern can normalize other strings accepted by NCL's integer conversion rules.


String Tricks

Exact-Width Multi-Character Padding

S.PADL and S.PADR add complete copies of the padding string, so a multi-character pad can exceed the requested length.

Trim the result when an exact width is required:

-- Left-pad to exactly 10 characters.

S.PADL $000 "42" "abc" 10
-- > $000 = "abcabcabc42"

S.SUB $000 $000 -10 -1
-- > $000 = "bcabcabc42"


-- Right-pad to exactly 10 characters.

S.PADR $000 "42" "abc" 10
-- > $000 = "42abcabcabc"

S.SUB $000 $000 0 9
-- > $000 = "42abcabcab"

Process a String Character by Character

S.MOVE $000 "Hello!"
S.LEN $001 $000
MOVE $002 0

:loop
BGE :done $002 $001

S.SUB $003 $000 $002 $002

-- Process $003 here.

INC $002
JUMP :loop

:done

String lengths and positions operate on complete Unicode characters, so characters outside the Basic Multilingual Plane still occupy one position.


Bit Tricks

Working with Bit Flags

Testing, setting, clearing, and toggling flags can all be done with the basic bitwise operations:

-- TEST bit 3.
AND $001 $000 8
BNEQ :set $001 0


-- SET bit 3.
OR $000 $000 8


-- CLEAR bit 3.
NOT $001 8
AND $000 $000 $001


-- TOGGLE bit 3.
XOR $000 $000 8

The mask 8 represents bit 3. Combine bits in the mask to operate on several flags at once.


Display Tricks

Update Several Fields Together

Prepare changes with D.TXT, then refresh the complete display once:

D.CUR 0 0
D.TXT "SYSTEM STATUS"

D.CUR 0 2
D.TXT "CPU: READY"

D.CUR 0 3
D.TXT "DRIVE: READY"

D.BLT

Use D.BLTN when the program does not need to wait for the refresh to complete.

Poll Input While Doing Other Work

SYS.KEY returns immediately with "" when no key is buffered:

:loop
SYS.KEY $000
S.BEQ :noInput $000 ""

-- Handle $000 here.

:noInput

-- Continue other work here.

JUMP :loop

Use SYS.AKEY instead when the program has nothing useful to do until input arrives.


Performance Tips

Coalesced Instructions

Short sequences that form one logical operation can share a program line:

RNG $000 6; INC $000

This reduces program-line fetch and dispatch overhead.

Do not coalesce merely to reduce line count. Separate lines are generally easier to label, branch to, and debug.

Remember that a taken branch or other write to pc ends execution of the current program line:

BEQ :done $000 0; D.TXT "NONZERO"

D.TXT executes only when the branch is not taken.


Common Pitfalls

Constants Do Not Recursively Expand

Constant substitution occurs once:

#foo 20
#bar #foo

MOVE $000 #bar

#bar becomes the literal text #foo. It is not subsequently expanded to 20.

The remaining unresolved symbol causes the program to fail during the pre-pass.


Definitions Are Last-Definition-Wins

The final definition is used throughout the program:

#value 10
#value 20

MOVE $000 #value
-- > $000 = 20

This also applies to built-in constants:

#TRUE 42

MOVE $000 #TRUE
-- > $000 = 42

Program Arguments Are Constants

Program arguments are exposed as #0 through #15 and follow the normal constant rules:

-- #0 was supplied by the caller.

#0 "replacement"

D.TXT #0
-- > prints "replacement"

The same applies to other built-in constants such as #THIS.


A New Program Invocation Has New CPU State

SYS.RUN, queued programs, and continuation through SYS.NEXT create new program invocations:

MOVE $000 42

SYS.NEXT #THIS :return 42
SYS.RUN "A:/OTHER.NCL" 0

:return
-- $000 from the previous invocation is not preserved.
MOVE $000 #0

RAM, the data stack, and the call stack from the previous invocation are not preserved. Pass required values as arguments or store them externally.


Repeated SYS.NEXT Calls Reverse Their Apparent Order

Each SYS.NEXT inserts at the front of the queue:

SYS.NEXT "A" 0
SYS.NEXT "B" 0

-- > B runs before A

Use SYS.QUEUE when insertion order should be preserved.


SHR and LSHR Are Different

SHR extends the sign bit; LSHR shifts zeroes into the high bits:

MOVE $000 -1

SHR $001 $000 1
-- > $001 = -1

LSHR $002 $000 1
-- > $002 = 2147483647

The difference matters when the high bit is set.


Multi-Character Padding May Exceed Its Requested Length

S.PADL and S.PADR add complete copies of their padding string:

S.PADL $000 "42" "abc" 10
-- > $000 = "abcabcabc42"
-- > length 11

Use the exact-width padding technique above when the final length must be exact.


Display Units Depend on the Operation

Horizontal D.SCR distances are measured in tiles, while east and west D.CRP distances are measured in characters:

D.SCR 1
-- > scrolls horizontally by 2 characters

D.CRP 0 1
-- > crops 1 character from the right

North and south distances are measured in rows.


D.BLTN Does Not Wait

D.TXT "Loading..."
D.BLTN

-- Program execution continues immediately.

Use D.BLT when subsequent behavior depends on the refresh having completed.


PRINT.NEW Is Destructive

PRINT.NEW discards any existing print job before starting a new one:

PRINT.NEW
PRINT.DATA "Old document"

PRINT.NEW
-- > "Old document" has been discarded

This also applies to a completed document awaiting pickup.

Use PRINT.CANCEL when the existing job should be discarded without starting another one.