
為什麼\setlength
環境內無效tabular
?這是一個 MWE:
\documentclass{article}
\newlength{\globallength}
\newlength{\locallength}
\begin{document}
\setlength{\globallength}{10pt}%
\begin{tabular}{l}
\setlength{\locallength}{10pt}%
\hspace*{10pt}. \\
\hspace*{\globallength}. \\
\hspace*{\locallength}. \\
\hspace*{0pt}. \\
\end{tabular}
\end{document}
雖然前兩個點對齊良好,但第三個點不同,並且表現得好像\locallength
一樣0pt
。為什麼會這樣,我能做什麼?我想在環境\setwidth
內部使用tabular
,因此在環境外部設定長度並不是真正的選擇。
答案1
對齊單元格在隱式組內進行處理,因此當組結束時,對變數的局部賦值將被撤消。
的內核定義\setlength
是
% latex.ltx, line 2181:
\def\setlength#1#2{#1 #2\relax}
這就是為什麼\global\setlength
似乎上班。另一方面, 的定義\settowidth
是
% latex.ltx, line 2187:
\def\settowidth {\@settodim\wd}
的定義\@settodim
是
% latex.ltx, line 2183:
\def\@settodim#1#2#3{\setbox\@tempboxa\hbox{{#3}}#2#1\@tempboxa
\setbox\@tempboxa\box\voidb@x}
這樣\global\settowidth{\locallength}{abc}
就會變成
\global\setbox\@tempboxa\hbox{{abc}}\locallength\wd\@tempboxa\setbox\@tempboxa\box\voidb@x
這當然對於對 進行全域分配是無效的\locallength
。
是的,\settowidth{\global\locallength}{abc}
會起作用,但這只是偶然。
LaTeX 不支援全域尺寸/跳過分配,您應該依賴較低層級的命令。所以更安全的方法是定義新指令:
\makeatletter
\newlength\local@length@for@global
\newcommand\gsetlength[2]{%
\setlength{\local@length@for@global}{#2}%
\global#1\local@length@for@global
}
\newcommand{\gsettowidth}[2]{%
\settowidth{\local@length@for@global}{#2}%
\global#1\local@length@for@global
}
\makeatother
\gsettoheight
如果需要的話,類似地\gsettodepth
。
即使calc
已加載,這也將起作用,並且不會利用“本地”命令的任何特定實作。
答案2
和\global\setlength{\locallength}{10pt}
似乎\setlength{\global\locallength}{10pt}
都有效,但我不知道為什麼需要這樣做。
https://tex.stackexchange.com/a/210598/30810讓我嘗試一下,@ChristianHupfer 的評論解釋了原因。
在我的較長文件中,\global\settowidth{...}
不起作用;\settowidth{\global...}
做過。