[Tex/LaTex] Variadic arguments macro

expansionmacrostex-core

I am trying to make macro with variadic arguments, iterating over them.
The final result is supposed to be:

\foreach[x]((var = \x )){foo}{bar}{baz}\null

evals to

var = foo var = bar var = baz

My naive guess is this one:

\def\Macro#1{\if \null#1 . \else ,\noexpand\Macro \fi}
\Macro foogg\null

I expected it to eval to ,,,,,., but it evals to ,oogg.
Am I understanding \noexpand behavior wrong?

Best Answer

Change \noexpand to \expandafter, that's what you need to "skip" that \fi. As well, as egreg points out, \if\null won't work. Either use \ifx, or change \null to \relax and hope it is not contained in your text. The reason why \relax will work is that it is unexpandable and \if takes it, instead of expanding. For the reason that \relax or \null might be used by someone else, a much safer option is to use a command that doesn't exist, like \thisIStoheczSdelimiter:

\def\Macro#1{\ifx\thisIStoheczSdelimiter#1 . \else ,\expandafter\Macro \fi}
\Macro foogg\thisIStoheczSdelimiter

As for working foreach cycles, look into pgffor package. Your code, IIRC, could be rewritten as

\foreach \x in {foo, bar, baz}{ var = \x, }
Related Question