Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Latex \newcommand variable number of arguments

Tags:

latex

tex

I'm trying to create a LaTeX -macro that basically does different things depending on how many arguments are passed to it.

Basically its function would be:

\MyMacro{4}
% Processes the argument and returns a set number of objects depending on the number

\MyMacro{4}{3}
% Processes the arguments in a slightly different way, including adding the numbers together

\MyMacro{4}{3}{6}
% Same thing as before, but the result is again processed slightly differently as before

\MyMacro{4}{3}{6}{2}{1}
% The maximum number of arguments the macro needs to handle is 5

I tried to implement the following TeX solution from an example I found online for up to 2 attributes, but it didn't like me.

\makeatletter
% Save first argument as \tempA
\def\MyMacro#1{\def\tempA{#1}\futurelet\next\MyMacro@i}

% Check for second argument
\def\MyMacro@i{\ifx\next\bgroup\expandafter\MyMacro@ii\else\expandafter\MyMacro@one\fi}

% Check for third argument
\def\MyMacro@ii{\ifx\next\bgroup\expandafter\MyMacro@iii\else\expandafter\MyMacro@two\fi}

% Check for fourth argument
\def\MyMacro@iii{\ifx\next\bgroup\expandafter\MyMacro@four\else\expandafter\MyMacro@three\fi}

\def\MyMacro@one{\section*{\tempA\ is the only argument}}
\def\MyMacro@two#1{\section*{\tempA\ is the first and #1 is the second argument}}
\def\MyMacro@three#1#2{\section*{\tempA\ is the first and #1 is the second argument with #2 being the third}}
\def\MyMacro@four#1#2#3{\section*{\tempA\ is the first and #1 is the second argument, #2 is the third and #3 is the fourth}}

\makeatother

It works for 1 or 4, but at 2-3 arguments, it gives me "Paragraph ended before \MyMacro@four was complete."

My grasp at basic TeX is very minimal, so I'd also appreciate a LaTeX solution as well using \newcommand, if possible.

Thanks!

like image 364
Joonas Joensuu Avatar asked Sep 20 '25 05:09

Joonas Joensuu


1 Answers

It seems that Werner's answer to a similar question is what you're looking for.

like image 83
User3419 Avatar answered Sep 23 '25 10:09

User3419