Z80 jump table
Posted: Sun Mar 18, 2018 11:55 pm
Just noticed you can do this to get a jump table on the Z80 (probably an old trick and I'm being a newbie, but whatever):
This relies on self-modifying code (it overwrites a jump), so you need to run this off RAM, but that's usually the case on the Mega Drive so no biggie. Also the index is quite limited due to overflow (maximum that works is 42), but it still should be large enough for most purposes. Beats having to do 16-bit arithmetic on an address when you can't ensure a table will be within a 256 byte boundary.
I'm multiplying the index by 3 since that's how long a JP instruction is (I'm assuming that the targets may be anywhere). If you can really ensure that all target addresses are close enough (within around 127 bytes*) then it'd look more like this:
By the way, the $ in that jump is just a placeholder (it'll be overwritten), I just picked something that would be within the allowed range so it can assemble.
*I say "around" since it needs to be 127 bytes away from the specific jump, so the actual maximum distance from the start of the code depends on which entry is being jumped to. Still should give a good idea of how far away it can afford to be.
Code: Select all
; a = index (0..42)
; b = spare
ld b, a ; Multiply index by 3
add a, b
add a, b
ld ($+4), a ; Overwrite the jump destination
jr $ ; Jump to the table
jp Routine1
jp Routine2
jp Routine3
...
I'm multiplying the index by 3 since that's how long a JP instruction is (I'm assuming that the targets may be anywhere). If you can really ensure that all target addresses are close enough (within around 127 bytes*) then it'd look more like this:
Code: Select all
; a = index (0..63)
add a, a ; Multiply index by 2
ld ($+4), a ; Overwrite the jump destination
jr $ ; Jump to the table
jr Routine1
jr Routine2
jr Routine3
...
*I say "around" since it needs to be 127 bytes away from the specific jump, so the actual maximum distance from the start of the code depends on which entry is being jumped to. Still should give a good idea of how far away it can afford to be.