如何全局设置 pgfmathsetlength?

如何全局设置 pgfmathsetlength?

如何通过pgfmathsetlength全局声明长度?

该示例的结果是 20 点 -- 5 点 -- 20 点 但我已经预料到了: 20 点 -- 5 点 -- 5 点

\documentclass[10pt]{article}
\parindent0pt
\usepackage{tikz}
\newlength\testl
\pgfmathsetlength\testl{20pt}
\begin{document}
\the\testl

{\global\pgfmathsetlength\testl{5pt}\the\testl}

\the\testl
\end{document}

我不想与\setlength或讨论可能性\deflength

答案1

你可以\global这样使用:

 {\pgfmathsetlength{\global\testl}{5pt}}\the\testl

一些评论:Egreg 注意到此代码与

\setlength{\global\testl}{5pt}

了解宏 pgfmathsetlength提供的内容可能很有趣。在文件中pgfmathcalc.code.tes我们可以读到:

% #1 = dimension register
% #2 = expression
%
% Description:
%
% These functions work similar to \setlength and \addtolength. Only,
% they allow #2 to contain an expression, which is evaluated before
% assignment. Furthermore, the font is setup before the assignment is
% done, so that dimensions like 1em are evaluated correctly.
%
% If #2 starts with "+", then a simple assignment is done (but the
% font is still setup). This is orders of magnitude faster than a
% parsed assignment.

声明全局长度的另一种可能性是重新定义,pgfmathsetlength但这不好,或者使用新的宏:globalpgfmathsetlength基于pgfmathsetlength。我们需要添加\global两行,但最简单的是我的第一个答案。

 \makeatletter
 \def\globalpgfmathsetlength#1#2{%
    \expandafter\pgfmath@onquick#2\pgfmath@%
    {%
        % Ok, quick version:
        \begingroup%
            \pgfmath@selectfont%
            \pgfmath@x#2\unskip%
            \pgfmath@returnone\pgfmath@x%
        \endgroup%
        \global#1\pgfmathresult pt\relax% here add \global before #1
    }%
    {%
        \pgfmathparse{#2}%
        \global#1\pgfmathresult pt\relax% and here
    }%
    \ignorespaces%
}  

答案2

使用临时尺寸

{\dimendef\temp=0
 \pgfmathsetlength\temp{5pt}\global\testl=\temp}

注意。我不会使用\testl来代替\temp,以避免“保存堆栈累积”。

相关内容