Skip to content
Bananattack edited this page Jun 20, 2011 · 11 revisions

The Language Reference - Branches

The ability to hop around within the code is useful, and so is branching on a condition, or indirectly jumping to a location based on a pointer in memory. The goto statement can handle these things.

Unconditional Jump

To directly jump to a new position in the code, use the syntax goto location, where location is an unsigned 16-bit integer value between 0..65535. (Opcode 0x4C, 6502 mnemonic jmp)

Indirect Jump

To indirectly jump to a new position in the code using a pointer to the location in memory, use the syntax goto [location], where location is an unsigned 16-bit integer value between 0..65535. (Opcode 0x6C, 6502 mnemonic jmp)

Addresses are stored in little-endian order. Note that the 6502 has a quirk if the location has the form 0x--FF (- means a "don't care" digit), where it grabs 0x--FF and 0x--00 instead of 0x--FF and (0x--FF + 1) (The low byte wraps around).

Conditional Branching

To conditionally jump to a new position in the code, depending on a conditional flag, then use the form goto location when condition, where condition is a status flag, location is an unsigned 16-bit integer value between 0..65535, and location is within an offset of -128 .. 127 bytes from the current rom position. For instance, goto foo when carry.

The condition can be prefixed by not to negate the flag, and branch when this condition is unset, rather than set. For example, goto loop when not zero.

These are possible conditions for use with goto location when condition:

Condition Opcode, Mnemonic
carry or >= (Opcode 0xB0, 6502 mnemonic bcs)
not carry or < (Opcode 0x90, 6502 mnemonic bcc)
zero or = (Opcode 0xF0, 6502 mnemonic beq)
not zero or <> (Opcode 0xD0, 6502 mnemonic bne)
overflow (Opcode 0x70, 6502 mnemonic bvs)
not overflow (Opcode 0x50, 6502 mnemonic bvc)
negative (Opcode 0x30, 6502 mnemonic bmi)
not negative (Opcode 0x10, 6502 mnemonic bpl)

If you need to jump further than the default `-128 .. 127` bytes, then you should replace code that looks like this:
goto foo when condition
// ...
def foo:

with something like this:

goto skip when not condition
goto foo
def skip:
//...
def foo: