# How to compare two counters using TeX conditionals in ConTeXt?

I have two counters, \definenumber[words] and \definenumber[items]. I have tried to use TeX conditionals to compare them, e.g.:

\ifnum\getnumber[words]=\getnumber[items]
This will print some text if the two counters have the same value.
fi


This does not work. How can I use TeX conditionals to compare two counters in ConTeXt?

-

\definenumber is a synonym for \definestructurecounter. You can use the expandable version \rawstructurecountervalue to get the value of the structure counter and use them in TeX conditionals.

An alternative is to use the commands.doifelse(...) lua function to do the comparison. I present both versions below (using named arguments so that the macro is easy to understand. Either save this in a file with an extension .mkvi or use % macros=mkvi on the first line of the .tex file).

% macros=mkvi

\unprotect

\unexpanded\def\strc_helper_compare#if#else#operator#counterA#counterB%
{\ctxcommand{doifelse(\rawstructurecountervalue[#counterA] #operator \rawstructurecountervalue[#counterB])}
{#if}{#else}}

\unexpanded\def\doifelsecomparestructurecounter
{\strc_helper_compare\firstoftwoarguments\secondoftwoarguments}

\unexpanded\def\doifcomparestructurecounter
{\strc_helper_compare\firstofoneargument\gobbleoneargument}
\protect

\definestructurecounter[one]
\definestructurecounter[two]

\setstructurecounter[one][1]
\setstructurecounter[two][2]

\starttext
\ifnum\rawstructurecountervalue[one]>\rawstructurecountervalue[two]\relax
One is bigger
\else
Two is bigger
\fi

\doifelsecomparestructurecounter{>=}{one}{two}{Counter one is bigger}{Counter two is bigger}
\doifelsecomparestructurecounter{<}{one}{two}{Counter one is smaller}{Counter two is smaller}
\doifcomparestructurecounter{<}{one}{two}{Counter one is smaller}
\doifcomparestructurecounter{>}{one}{two}{Counter two is smaller}
\stoptext

-