If Most Recent Instance of a Block Contains X in Y Field Then Do Z I’m looping through blocks in a matrix field on a page. In multiple different blocks in that loop, all of which could be different block types, I’d like to have an if statement that basically says if the most recent instance of a particular block type (we'll call it "referenceBlockType") contains x in y field, then do z. Note that by most recent instance I mean the closest previous instance of referenceBlockType relative to the position of the block that contains the if statement.

referenceBlockType appears multiple times in the loop and is not necessarily a direct sibling of the block that is referencing it, nor is it always the first or last field in the loop.

How would I do that? Thanks!
My answer is based on the assumption you only have one matrix module you want to compare, otherwise you would have to store your values in an array with the key as block.getType().handle or you would have to create multiple variables.

You want to create a variable that stores the value of your field if the block handle matches. So you check if your handles are equal and compare them

{% set latestBlockValue = null %}
{% for block in entry.matrix %}
    {% if block.getType().handle == 'referenceBlockType' %}
        {% if latestBlockValue is not null and latestBlockValue == x %}
            {# z #}
        {% endif %}
        {% set latestBlockValue = block.y %}
    {% endif %}
{% endfor %}