If the number of arguments is not known, one can use pgfkeys
for something like this:
\documentclass{article}
\usepackage{pgfkeys,pgffor}
\newcounter{mainargs}
\pgfkeys{mainargs/.is family, mainargs,
step counter/.code=\stepcounter{mainargs},
add argument/.style={step counter, arg\themainargs/.initial={#1}},
}
\newcounter{optargs}
\newif\ifoptargs
\pgfkeys{optargs/.is family, optargs,
opt args present/.is if=optargs,
step counter/.code=\stepcounter{optargs},
add argument/.style={opt args present=true, step counter, arg\theoptargs/.initial={#1}},
}
\newcommand{\mycommand}[2][]{%
\setcounter{mainargs}{0}%
\pgfkeys{mainargs, add argument/.list={#2}}%
\setcounter{optargs}{0}%
\pgfkeys{optargs, add argument/.list={#1}}%
%
main arguments:\\%
\foreach \n in {1,...,\themainargs}{%
\pgfkeysvalueof{/mainargs/arg\n}\\%
}%
%
\ifoptargs%
optional arguments:\\%
\foreach \n in {1,...,\theoptargs}{%
\pgfkeysvalueof{/optargs/arg\n}\\%
}%
\fi%
}
\parindent=0pt
\begin{document}
\mycommand{foo, bar}\\
\mycommand[a,b]{foo, bar, baz}
\end{document}
Of course, if the number of arguments is known, one can use \pgfkeysvalueof{/mainargs/arg1}
, \pgfkeysvalueof{/mainargs/arg2}
, etc. without the foreach
loop.
As the argument values are available even after the execution of the command finished, it is probably safer to use a group to keep the definitions local or to define reset keys like:
\pgfkeys{mainargs,
reset one arg/.style={arg#1/.initial={}},
reset args/.style={reset one arg/.list={1,...,\themainargs}}
}
\pgfkeys{optargs,
reset one arg/.style={arg#1/.initial={}},
reset args/.style={reset one arg/.list={1,...,\theoptargs}, opt args present=false}
}
Then one should call them at the end of the command definition:
\pgfkeys{mainargs, reset args}
\pgfkeys{optargs, reset args}
The complete command with the formatting used in the question is:
\newcommand{\mycommand}[2][]{%
\setcounter{mainargs}{0}%
\pgfkeys{mainargs, add argument/.list={#2}}%
\setcounter{optargs}{0}%
\pgfkeys{optargs, add argument/.list={#1}}%
%
\ifoptargs%
optional: %
\pgfkeysvalueof{/optargs/arg1}
\ifnum\theoptargs>1%
\foreach \n in {2,...,\theoptargs}{%
--- \pgfkeysvalueof{/optargs/arg\n}%
}%
\fi\\%
\pgfkeys{optargs, reset args}%
\fi%
%
mandatory: %
\pgfkeysvalueof{/mainargs/arg1}
\ifnum\themainargs>1%
\foreach \n in {2,...,\themainargs}{%
--- \pgfkeysvalueof{/mainargs/arg\n}%
}%
\fi%
%
\pgfkeys{mainargs, reset args}%
}