How to detect "empty" elements inside a tikz \foreach statement
The problem in the macro from the question:
\newcommand\Macro[1]{%
\foreach \x in {#1} {
\if\relax\detokenize{\x}\relax Empty!
\else x=\x.
\fi
}
}
is that \detokenize
does not expand its argument and returns the two tokens \
and x
. This is cured by adding an \expandafter
:
\detokenize\expandafter{\x}
The full macro:
\newcommand\Macro[1]{%
\foreach \x in {#1} {
\if\relax\detokenize\expandafter{\x}\relax Empty!
\else x=\x.
\fi
}
}
Something like this?
\documentclass{article}
\usepackage{tikz}
\newcommand\Macro[1]{%
\foreach \x in {#1} {
\ifx\x\empty\relax Empty!
\else x=\x.
\fi
}
}
\begin{document}
\Macro{,,,4,5,5}
\end{document}
The mandatory expl3
answer (after noting that \detokenize\expandafter{\x}
would be the solution):
\documentclass{article}
\usepackage{tikz}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand{\blankTF}{mmm}
{% #1 = text to test, #2 = blank case, #3 = non blank case
\str_if_eq_x:nnTF { #1 } { } { #2 } { #3 }
}
\NewDocumentCommand{\lforeach}{O{,}mm}
{% #1 = delimiter, #2 = list, #3 = code
\seq_set_split:Nnn \l_andrew_foreach_seq { #1 } { #2 }
\seq_map_inline:Nn \l_andrew_foreach_seq { #3 }
}
\ExplSyntaxOff
\newcommand\Macro[1]{%
\lforeach{#1}{%
\blankTF{##1}{Empty!}{$|$##1$|$.}
}
}
\begin{document}
\lforeach[-]{a-b--\texttt{c}}{%
\blankTF{#1}{Empty!}{$|$#1$|$.}
}
\lforeach{, ,,4, 5 ,5}{%
\blankTF{#1}{Empty!}{$|$#1$|$.}
}
\Macro{, ,,4, 5 ,5}
\end{document}
The current item in the cycle is denoted by #1
(which has to become ##1
in the definition of \Macro
).