This question is an extension to Defining command part by part thread. Let's say we have a command \foo
with 1 argument. Can we produce a command \setfoo{aaa}{<some stuff>}
which redefines \foo
to: if an argument of \foo
is equal to 'aaa', do 'some stuff'; otherwise do what \foo was supposed to do previously? I would also like to use \setfoo many times, so
\setfoo{a}{part1}
\setfoo{b}{part2}
\setfoo{c}{part3}
\foo{a} \foo{b} \foo{c}
would produce
part1 part2 part3
Additionally, I want to be able to use \setfoo
inside enumerate
, and then use \foo
inside or outside, so
\begin{enumerate}
\item First item. \setfoo{1}{part 1}
\setfoo{2}{part 2}
\item Second item.
\item Some text \setfoo{3}{part 3} Some text \foo{1}
\end{enumerate}
\foo{1} \foo{2} \foo{3}
would give
1. First item.
2. Second item.
3. Some text Some text part 1
part 1 part 2 part 3
I've tried egreg's solution from previous question, but all \foo
s beyond \end{enumerate}
were undefined. MWE:
\documentclass{article}
\newcommand{\setfoo}[2]{%
\expandafter\newcommand\csname tomasz@#1\endcsname{#2}%
}
\makeatletter
\newcommand{\foo}[1]{%
\ifcsname tomasz@#1\endcsname
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
{\csname tomasz@#1\endcsname}%
{BUMMER!}%
}
\makeatother
\begin{document}
\begin{enumerate}
\item First item. \setfoo{1}{part 1}
\setfoo{2}{part 2}
\item Second item.
\item Some text \setfoo{3}{part 3} Some text \foo{1}
\end{enumerate}
\foo{1} \foo{2} \foo{3}
\end{document}
This produces:
1. First item.
2. Second item.
3. Some text Some text part 1
BUMMER! BUMMER! BUMMER!
(BUMMER! is the output of \foo{<x>}
when \setfoo{<x>}{<something>}
was not used before.)
If it makes the problem easier, I could only use numbers as arguments of \foo
, but I would appreciate general solution (when arguments of \foo
are some strings of letters/numbers).