
我有一個命令\yesifone
應該採用1
or0
作為參數,並且根據這兩種情況表現不同。我想將命令的輸出傳遞給它\one
。但是,\one
依賴一些其他\blah
不生成輸出的命令(在我的具體情況下,它設定一個變數)。我目前的嘗試失敗了,大概是因為比較ifnum
包含了\blah{}
,而不僅僅是 number 1
。我怎樣才能做到這一點,例如透過忽略\blah{}
呼叫並僅檢查輸出文字?
換句話說,我希望輸出以下內容yes
。
\documentclass{minimal}
\begin{document}
\newcommand{\blah}{}
\newcommand{\one}{
\blah{}
1
}
\newcommand{\yesifone}[1]{%
\ifnum1=#1\relax{yes}\else{no}\fi
}
\yesifone{\one} % error: Missing number, treated as zero.
\end{document}
答案1
使用您的程式碼\yesifone{\one}
會產生令牌
\yesifone{1\one}2
這擴展到.
\ifnum112=12\one\relax{1y11e11s11}2\else{1n11o11}2\fi
\ifnum收集屬於 的第二個 TeX-⟨ 的代幣時數位⟩-數量,即 後面的數字,令牌被擴展,因此你有 s.th.喜歡=12\one
\ifnum112=12␣10\blah{1}2␣10112␣10\relax{1y11e11s11}2\else{1n11o11}2\fi。
後面的空格標記被刪除並擴展,然後隨著替換文字為空而消失。因此你有某物。喜歡:␣10=12\blah
\ifnum112=12{1}2␣10112␣10\relax{1y11e11s11}2\else{1n11o11}2\fi。
\ifnum所以在收集屬於 的第二個 TeX-⟨ 的代幣時數位⟩-數量,即 後面的數字,TeX 找到一個空的大括號組,即顯式字元標記和,它絕對不構成形成有效 TeX-⟨ 的標記序列的開頭=12{1}2數位⟩-數量。
想想 Knuth 將 TeX 比喻為一頭有眼睛和消化道的野獸。
- 可擴展令牌的擴展在某種反流過程中發生在食道中,除非擴展被抑制,例如,對於形成參數文字或賦值的替換文字的令牌
\def
。 (LaTeX\newcomand
等\NewDocumentCommand
是用於呼叫的複雜包裝器\def
。) - 任務在胃中進行。
因此,將諸如為「變數」賦值之類的任務與需要進行非排版工作的胃與食道/可擴展標記的擴展就足夠的任務以及食道後面的消化器官僅涉及排版的任務分開:
\documentclass{minimal}
% Introduce/initialize things used as variable whose value is
% to be set via assignments that take place in the stomach:
\newcommand\VariableRelatedToBlah{}
% Define macros for tasks that involve digestive organs behind the gullet for
% for non-typesetting-tasks, e.g.,_setting_ values of variables via assignments:
\newcommand\SetValueOfVariableRelatedToBlah[1]{%
\def\VariableRelatedToBlah{#1}%
}
% Define macros for tasks that involve only the gullet, e.g.,
% _retrieving_ values of variables, or additionally to the gullet
% involve digestive organs behind the gullet only for typesetting:
\newcommand\RetrieveValueOfVariableRelatedToBlah{%
\VariableRelatedToBlah
}
\newcommand\firstofone[1]{#1}%
\newcommand{\yesifone}[1]{%
\ifnum1=\expandafter\firstofone\expandafter{\number#1} yes\else no\fi
}
\begin{document}
% Now you can keep work that involves the stomach for non-typesetting
% separated from work where the gullet is sufficient/where tokens
% delivered by the gullet can directly be used for typesetting:
\SetValueOfVariableRelatedToBlah{0}%
\yesifone{\RetrieveValueOfVariableRelatedToBlah}
\SetValueOfVariableRelatedToBlah{1}%
\yesifone{\RetrieveValueOfVariableRelatedToBlah}
\end{document}