Tutorial · Chapter 6 of 23

Pass values through inline assembly

Send data to a 6502 instruction, capture a result, and follow the compiler's register wrapper.

Jump to a section

Read parameters and write source variables

Start with the two data paths in adjustedX. A by-value record parameter supplies actor.pos.x through @actor_pos_x. The byte parameter delta has its own cell. Write the sum into @result before leaving the block so the ZeroPage return statement can read it.

Byte parameters, a nested field, and a mutable result
fn adjustedX(actor: Actor, delta: u8) u8 {
    var result: u8 = 0;
    asm {
        lda @actor_pos_x
        clc
        adc @delta
        sta @result
    }
    return result;
}

The main program also uses the flattened operand for a mutable local record. It increments the local X from 3 to 4 and replaces its mode tag. The function adds 1 to its copy of X and returns 5. Expect X 05 MODE 02.

Open the complete source

Follow register restoration through a firmware call

KERNAL GETIN returns the keyboard byte in A. An external jsr makes the compiler save P, A, X, and Y before the block. The sta @key captures the value while A still holds it. The wrapper then pulls Y, X, A, and P, leaving the byte in key for the function to return.

Source block

Inside readKey
asm {
    jsr $ffe4
    sta @key
}

Generated instruction order

Storage label shortened
php
pha
txa
pha
tya
pha
jsr $ffe4
sta readKey_key
pla
tay
pla
tax
pla
plp

Flags are restored last because the preceding pulls and transfers can change them. An instruction that only writes memory can have fewer clobbers. See the preservation table for the per-instruction rules. For a firmware condition reported in carry, branch on carry inside the block and write a Boolean cell on success.

Open the complete source

Press A at the prompt. Expect KEY 41 under the default C64 keyboard mapping. The value comes from a source variable after the register wrapper has finished.

Choose an operand form from what the instruction needs

NeedFormWhat it supplies
Read a source bytelda @deltaThe byte in the parameter cell.
Store into a nested recordsta @actor_pos_xThe byte field of a mutable record.
Address a stringldx #<@text.data
ldy #>@text.data
Low and high immediate address bytes.
Read a string lengthlda #@text.len for a constant
lda @msg.len for a buffer
An immediate length or a mutable runtime length cell.

Keep an ordinary word or pointer out of a bare @name operand. Pass a word as named low and high bytes. For an indirect load, initialize a reserved zero-page pair with an address and restore borrowed bytes when done. The string and indirect walkthrough shows indexed data and a complete example using ($30),y.

Try adding one to $12ff in the word example. The low-byte addition carries into the high byte. Expect COUNTER 1300. The block's two stores carry the answer back into ZeroPage, where the function joins the bytes into a word.

Open the complete source