正在查找 \providelength

正在查找 \providelength

我需要一个类似于的宏\providecommand\providelength{\lengthName}{0.5cm}如果尚不存在,应该给我一个新的长度。如果没有给出所需的值,我想使用宏来设置 TikzPicture 的标准值。我在网上找到了以下代码,但它不起作用:

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}

\makeatletter
\newcommand*\providelength[1]{%
  \begingroup
    \escapechar\m@ne
    \xdef\@gtempa{\string#1}%
  \endgroup
  \@ifundefined{\@gtempa}%
    {\newskip#1}%
    {}%
}
\makeatother

\begin{document}
  \providelength{\ltest}{0.1pt}
  \the\ltest

\end{document}

本文档的输出是

0.1pt
0.0pt

因此,该命令似乎根本没有效果。相反,参数被打印出来。有人知道如何解决这个问题吗?

答案1

我的解决方案假设\长度寄存器名称的开头有一个字符,它没有经过测试tikz等等。

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{etoolbox}%
\usepackage{ifmtarg}%


\makeatletter
\newcommand*{\otherprovidelength}[2]{%
  \begingroup
    \escapechar\m@ne
    \xdef\@gtempa{\string#1}%
  \endgroup
  \@ifundefined{\@gtempa}%
    {\newskip#1%
     #1=#2}%  Assign the 2nd argument.
    {}%
}
\makeatother



\providecommand{\providelength}[2]{%
\ifdeflength{#1}{% It is already defined!
}{% Not defined, so define it!
\newlength{#1}%
}%
\setlength{#1}{#2}%
}%

\makeatletter
\providecommand{\ProvideLength}[2][]{%
% Check, if the command is already defined, if not, then define it!
\ifdeflength{#2}{% It is already defined!
\GenericWarning{}{Warning: Length #2 already defined!!!!!!!!} % Optional
}{% Not defined, so define it!
\newlength{#2}%
}%
\@ifmtarg{#1}{%  is 1st argument empty -> do not set the length at all!
}{% Set the length to the value of the 1st argument.
\setlength{#2}{#1}%  
}% End of \@ifmtarg
}% End of \providecommand
\makeatother



\begin{document}
  \providelength{\ltest}{0.01pt}
  \the\ltest \par
% Some testing
  \addtolength{\ltest}{0.05pt}
  \the\ltest \par 

  \ProvideLength[0.17pt]{\ltesttwo}
  \ProvideLength{\lyetanotherlength} % initialized to 0.0pt if undefined before
 \the\ltesttwo \par
 \the\lyetanotherlength
\end{document}

编辑:

我添加了另一个命令\ProvideLength,该命令将长度值作为可选的第一个参数,将长度寄存器名称作为第二个参数。如果长度寄存器已存在,它还会生成警告。

我把 Simon 的命令改为,\otherprovidelength并添加了缺失的第二个参数以及跳过寄存器的分配。

相关内容