![新命令:將座標作為單一參數傳遞](https://rvso.com/image/305778/%E6%96%B0%E5%91%BD%E4%BB%A4%EF%BC%9A%E5%B0%87%E5%BA%A7%E6%A8%99%E4%BD%9C%E7%82%BA%E5%96%AE%E4%B8%80%E5%8F%83%E6%95%B8%E5%82%B3%E9%81%9E.png)
是否可以將數組參數傳遞給newcommand
然後存取這些單獨的數組元素?
例如,如果我想將陣列的第三個元素(第一個參數)乘以第二個參數的值:
\newcommand{\hello}[2]{(#1.#3)*#2}
(注意#1.#3可能不正確,我問如何存取這個值。)
並在主體程式碼中使用命令:
I want \hello{1,2,5}{2} gumdrops.
編輯:最小工作範例?
\documentclass{standalone}
\newcommand{\hello}[2]{(#1)*(#2)}
\begin{document}
I want \hello{1}{2} gumdrops.
\end{document}
它並不是真正的乘法(我想我不知道如何將數字相乘newcommand
),但這對我來說並不重要,無論哪種方式我都希望能夠存取參數的值。除了第一個參數之外,我希望能夠傳遞一個陣列並存取它的每個特定元素單獨地(即不循環它),這在 MWE 中完全沒有表達。
答案1
以下內容可能適合您:
\documentclass{article}
\usepackage{etoolbox,xparse}
\ExplSyntaxOn
\cs_new_eq:NN \CALC \fp_eval:n
\ExplSyntaxOff
\newcounter{argcnt}
\makeatletter
\newcommand{\newarray}[2]{% \newarray{<array>}{<csv list>}
\setcounter{argcnt}{0}% Restart argument count
\renewcommand{\do}[1]{% With each element do...
\stepcounter{argcnt}% Next arg
\expandafter\gdef\csname #1@\theargcnt\endcsname{##1}% Store arg in \<array>@<num>
}%
\docsvlist{#2}% Store array
\expandafter\xdef\csname #1@0\endcsname{\theargcnt}% Store array element count
}
\newcommand{\getelement}[2]{% \getelement{<array>}{<num>}
\@ifundefined{#1@0}% <array> not defined
{\@latex@error{Array #1 undefined}\@ehc}{}
\expandafter\ifnum\csname #1@0\endcsname<#2 % <num> out of range
\@latex@error{Array #1 only has \csname #1@0\endcsname\space elements}\@ehc
\fi
\csname #1@#2\endcsname% Print element
}
\newcommand{\calc}[1]{\expandafter\CALC\expandafter{#1}}% calculations
\makeatother
\begin{document}
\newarray{arrayA}{a,b,c}%
\newarray{arrayB}{1,2,3}%
\getelement{arrayA}{1}
$2 \times \getelement{arrayB}{2} + \getelement{arrayB}{3} = \calc{2*\getelement{arrayB}{2}+\getelement{arrayB}{3}}$
\end{document}
\newarray{<array>}{<csv list>}
<array>
使用逗號分隔值清單中包含的元素建立陣列<csv list>
。\getelement{<array>}{<num>}
其作用類似數組索引,而\calc
可用於執行計算數位元素。
該方法允許您在數組中儲存幾乎任何內容,而不僅僅是數字(和/或混合它們)。
答案2
這跟你的意思是一樣的嗎?也許這可以幫助你開始。
\documentclass{article}
\newcommand{\twothings}[2]{%
\gdef\thingone{#1}
\gdef\thingtwo{#2}
}
\newcommand{\pickone}[1]{%
\ifnum#1 = 1
\thingone
\else
\ifnum#1 = 2
\thingtwo
\else
\relax
\fi
\fi%
}
\begin{document}
\twothings{First}{Second}
The second thing is \pickone{2}.
\end{document}