假设我写了两个命令,CommandA 和 CommandB。我希望有第三个命令,它接受输入来确定执行前两个命令中的哪一个。我非常天真地尝试这样做并实现这一点,如下所示,但是,它不起作用。
\newcommand{CommandA}{
\hspace{5mm}
}
\newcommand{CommandB}{
\vspace{5mm}
}
\newcommand{C}[1]{
\Command#1
}
因此,如果我调用\C{A}
,正如所写,我就会真正执行\CommandA
。
答案1
对于普通用户来说,这可能是最容易理解的
\usepackage{etoolbox}
\newcommand{\CommandA}{%
\hspace{5mm}%
}
\newcommand{\CommandB}{%
\vspace{5mm}%
}
\newcommand\C[1]{%
\csuse{Command#1}%
}
\csuse
建立一个宏名并调用它
答案2
定义是有意义的家庭此类命令。
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\defineobject}{mm}
{
\prop_new:c { g_garth_#1_prop }
\prop_gset_from_keyval:cn { g_garth_#1_prop } { #2 }
}
\NewDocumentCommand{\getobject}{mm}
{% #1 = object name, #2 = variable or string
\prop_item:cf { g_garth_#1_prop } { #2 }
}
\cs_generate_variant:Nn \prop_item:Nn { cf }
\ExplSyntaxOff
\defineobject{C}{
A=\hspace{5mm},
B=\vspace{5mm}
}
\newcommand{\C}[1]{\getobject{C}{#1}}
\begin{document}
X\C{A}Y\C{B}
XYZ
\end{document}
这可能对类似问题有用你能在 LaTex 中创建连接变量名吗?
\documentclass[12pt]{exam}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\defineobject}{mm}
{
\prop_new:c { g_garth_#1_prop }
\prop_gset_from_keyval:cn { g_garth_#1_prop } { #2 }
}
\NewDocumentCommand{\getobject}{mm}
{% #1 = object name, #2 = variable or string
\prop_item:cf { g_garth_#1_prop } { #2 }
}
\cs_generate_variant:Nn \prop_item:Nn { cf }
\ExplSyntaxOff
\defineobject{fun}{
A={$s(t) = 12t^2 -7t + 16$},
B={$s(t) = 16t^2 +3t + 10$},
C={$s(t) = 12t^2 + t + 10.$}
}
\newcommand{\exam}{A}
\begin{document}
\begin{questions}
\question
The position of an object moving along a straight line is given by
\getobject{fun}{\exam}. Find the average velocity of the object over
the interval $[1,1+h]$ where $h>0$ is a real number.
\renewcommand{\exam}{B} % just for testing
\question
The position of an object moving along a straight line is given by
\getobject{fun}{\exam}. Find the average velocity of the object over
the interval $[1,1+h]$ where $h>0$ is a real number.
\end{questions}
\end{document}
第二个问题进行了修改,\exam
只是为了测试是否获得了预期的输出。您可以根据需要定义任意数量的对象。如果只有一个变量\exam
,定义一个简写也是有意义的:
\newcommand{\obj}[1]{\getobject{#1}{\exam}}
然后上面的调用就可以更简单了\obj{fun}
。
答案3
\documentclass{article}
\newcommand\exchange[2]{#2#1}%
\newcommand\name{}%
\long\def\name#1#{\romannumeral0\innername{#1}}%
\newcommand\innername[2]{%
\expandafter\exchange\expandafter{\csname#2\endcsname}{ #1}%
}%
\name\newcommand{CommandA}{%
\hspace{5mm}%
}
\name\newcommand{CommandB}{%
\vspace{5mm}%
}
\name\newcommand{C}[1]{%
\name{Command#1}%
}
\begin{document}
\hbox{\hbox{X}\C{A}\hbox{X}}%
\C{B}%
\hbox{\hbox{X}\C{A}\hbox{X}}%
\end{document}