Rules

You might know this as Decision tables, I think the DOD book called them tables (although my brain got a little confused in that part of the book).

Some time ago I wrote a little abstraction that let you pass function pointers into a tagged allocator, and given the correct combination of tagged memory, the function would run.

I'm not a super fan of code that has tones of abstractions in it. So I didn't want to port that code over to this project.

ℹ️
'Prefer Vanilla and Iteration' is literally the first line of my code standards.

So I did this instead.

void update() {
        RULE(state, STATE_A | STATE_B, STATE_C) {
                /* This chunk of code only executes if STATE_A and _B
                 * exist in `state`, and STATE_C bit is off.
                 */
        }
}

The state flags are just Power of 2 numbers defined like this ...

enum {
        STATE_A = 1 << 0,
        STATE_B = 1 << 1,
        STATE_C = 1 << 2,
};

And the macro is defined as ...

#define RULE(st, on, off) ((st & (on|off)) == (uint32_t)(on))

This means for chunks of code you can set specific the flags that must be 'on' and flags that must be 'off'.

RULE(state, STATE_INPUT | STATE_FREECAM, 0) {
         UpdateDebugCamera();
}

RULE(state, STATE_INPUT, STATE_FREECAM) {
        UpdateFPSCamera();
}

RULE(state, 0, STATE_PICKUP | STATE_FREECAM) {
        InteractionTest();
}

RULE(state, STATE_INPUT | STATE_PICKUP, STATE_FREECAM) {
        DropBoxTest();
}

RULE(state, STATE_PICKUP, 0) {
        UpdatePickedUpObject();
}
Examples I currently have in the repo.

Conceptually you can get the same functionality with a whole lot of if statements, but I prefer these for larger chunks of logic. I try to always have a 1:1 representation of State and Data, meaning each flag represents some structure of data, but occasionally pure events work there way into the list. NETWORK_DOWN as an example. You also limited to 64 types of data, so making a state for every single datatype is out the question although yes you could take another angle on this, but we get into 'too complicated for the time I have available' territory.

There might be a time when I have to look at allocations again, and if that time comes I may look again at tagged allocations + functions, but that's something to think about some other time.So

Subscribe to Republic Of Almost

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe