I have looked through answers on this forum that did bring me closer to the solution of the problem stated above, but both the approach via \xdef and via \g@addto@macro give errors or wrong results.
What I want to do is to define a macro with an optional argument that is parsed in a loop: the input \gttest[Mg=x,Fe=y,Ca=z] is supposed to create a chemical formula of the form Mg_x Fe_y Ca_(1-x-y); spaces and parens are given here for clarity only and don't appear in the actual output. Here is the code (part of a .sty file):
\RequirePackage{xspace}
\RequirePackage{xstring}
\RequirePackage{ifthen}
\RequirePackage{fp-eval}
\RequirePackage{twoopt}
% preliminaries for the components
\newcommand{\@sublow}{\vphantom{A}}
\newcommand{\@chem}[2]{%
\ifthenelse{\equal{#2}{1}}{#1}{%
\ensuremath{\mathrm{#1}\@sublow_{#2}}}}
\newcommand{\@GCresb}{}
\newcommand{\@GCresc}{}
\newcommand{\@GCtmpa}{}
\newcommand{\@GCtmpb}{}
\newcommand{\@GCtmpc}{}
\newcommand{\@GCtmpd}{}
\newcounter{isscmp}
\newcounter{jsscmp}
\newcounter{lsscmp}
\newcounter{nsscmp}
% the actual macro
\newcommand{\gttest}[1][]{%
\StrCount{#1}{=}[\nsscmp]%
\setcounter{lsscmp}{\nsscmp}%
\setcounter{isscmp}{0}%
\setcounter{nsscmp}{1}%
\renewcommand{\@GCtmpa}{}%
\renewcommand{\@GCresc}{}%
\whiledo{\value{nsscmp}<\value{lsscmp}\OR\value{nsscmp}=\value{lsscmp}}{%
\ifthenelse{\value{nsscmp}<\value{lsscmp}}{%
\StrPosition[\thensscmp]{#1}{,}[\jsscmp]%
\StrMid{#1}{\value{isscmp}+1}{\numexpr\jsscmp-1}[\@GCtmpb]}{%
\StrGobbleLeft{#1}{\value{isscmp}}[\@GCtmpb]}%
\StrBefore{\@GCtmpb}{=}[\@GCtmpc]%
\StrBehind{\@GCtmpb}{=}[\@GCtmpd]%
\ifthenelse{\value{nsscmp}<\value{lsscmp}}{%
% all but last comp.: use given subscript and accumulate
\xdef\@GCresc{\@GCresc-\@GCtmpd}%
\renewcommand{\@GCresb}{\@chem{\@GCtmpc}{\@GCtmpd}}}{%
% last comp.: apply closure condition \sum x_i=1
\renewcommand{\@GCresb}{\@chem{\@GCtmpc}{1\@GCresc}}}%
\xdef\@GCtmpa{\@GCtmpa\@GCresb}% <-- causes Incomplete iffalse
%\g@addto@macro\@GCtmpa{\@GCresb}% <-- produces wrong result
\setcounter{isscmp}{\jsscmp}%
\stepcounter{nsscmp}}%
\@GCtmpa}
In this form, the code throws an error:
! Incomplete \iffalse; all text was ignored after line 5.
\fi
<*> mytest
If I comment the xdef line signaled with the <-- and uncomment the following line with the g@addto... instead, it runs smoothly but the result is
Ca_(1-x-y) Ca_(1-x-y) Ca_(1-x-y)
So - why doesn't this work? I have no idea where an incomplete if clause would be in the first variant nor how the last appendage gets to be repeated three times in the second variant, although the argument is correctly parsed.

zwhen it's converted to1-x-y? – Werner Oct 7 '12 at 2:21