Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

\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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.