z80:LUT/Jump Tables

From Learn @ Cemetech
Jump to: navigation, search

Look-up tables (LUTs)

To make a look-up table (LUT), you must set the bounds. Look-up tables are often used in calculations which are not easy to find with arithmetic, such as the sine function. Lets model the sine function with a look-up table.


   LD     H, 0
       LD     L, A
       LD     DE, sine_table
       ADD    HL, DE
       LD     A, (HL)
       INC    HL
       LD     H, (HL)
       LD     L, A
       RET
   sine_table:
       ; The lookup table
   .DW    $0000, $0004, $0009, $000D, $0012, $0016, $001B, $001F, $0024
   .DW    $0028, $002C, $0031, $0035, $003A, $003E, $0042, $0047, $004B
   .DW    $004F, $0053, $0058, $005C, $0060, $0064, $0068, $006C, $0070
   .DW    $0074, $0078, $007C, $0080, $0084, $0088, $008B, $008F, $0093
   .DW    $0096, $009A, $009E, $00A1, $00A5, $00A8, $00AB, $00AF, $00B2
   .DW    $00B5, $00B8, $00BB, $00BE, $00C1, $00C4, $00C7, $00CA, $00CC
   .DW    $00CF, $00D2, $00D4, $00D7, $00D9, $00DB, $00DE, $00E0, $00E2
   .DW    $00E4, $00E6, $00E8, $00EA, $00EC, $00ED, $00EF, $00F1, $00F2
   .DW    $00F3, $00F5, $00F6, $00F7, $00F8, $00F9, $00FA, $00FB, $00FC
   .DW    $00FD, $00FE, $00FE, $00FF, $00FF, $00FF, $0100, $0100, $0100


The main disadvantage is the size, but we can't do much about it.

Jump Tables

These are just like LUTs, except that rather than values being returned, they return an area in memory.

A vector table holds only the addresses. Here is an example:


   VectTbl:
       .DW     ClearScreen
       .DW     PutSprite
       .DW     DrawLine
       .DW     EndPrgm
       .DW     BlackScreen
   
       LD     H, 0
       LD     L, A
       LD     HL, HL
       LD     DE, VectTbl
       ADD    HL, DE;Just like a look-up table
   
       LD     A, (HL)
       INC    HL
       LD     H, (HL)
       LD     L, A
       JP     (HL)


A Jump table is essentially a vector table, but rather than holding the address, it holds the entire jump instruction.


   JumpTbl:
       JP    ClearScreen
       JP    PutSprite
       JP    DrawLine
       JP    EndPrgm
       JP    BlackScreen


To call or jump to a routine in the jump table, you use an address of JumpTbl + 3 * n where n is the number of the routine you want. Supposing you wanted to run DrawLine, then you would use CALL JumpTbl + 3 * 2

If you notice, the default B_CALLs have offsets of 3. For example, B_CALL(_ClrLCDFull) is EF4045 in machine code, and B_CALL(_ClrLCD) is EF4345 in machine code, and B_CALL(_ClrScreenFull) is EF4645. EF is BCALL(**). But why is the first byte of the address increasing? This is because the calculators use Little-Endian; the least-significant-byte and most-significant-byte are essentially swapped.