\foreach 中 listofitems 列表的长度错误...

\foreach 中 listofitems 列表的长度错误...

当我回答的时候另一个问题,我发现了错误

! Illegal unit of measure (pt inserted).

仅当我...在列表中使用\foreach一个简单的列表长度操作时:

\documentclass{article}
\usepackage{tikz}
\usepackage{listofitems}
\setsepchar{;}

\begin{document}

\readlist\points{(1,2); (2,3); (3,2); (1,1); (2,2)}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,2,3,4}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,...,4}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,2,3,\pointslen-1}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

This gives the error 
\texttt{! Illegal unit of measure (pt inserted).}
\begin{tikzpicture}
    \foreach \i  in {1,...,\pointslen-1}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}
\end{document}

答案1

不确定实际问题出在哪里(虽然我猜测是在\foreach极限评估器中),但将可疑项括在里面\numexpr...\relax(以评估整数)可以解决问题。

\documentclass{article}
\usepackage{tikz}
\usepackage{listofitems}
\setsepchar{;}

\begin{document}

\readlist\points{(1,2); (2,3); (3,2); (1,1); (2,2)}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,2,3,4}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,...,4}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

This works:
\begin{tikzpicture}
    \foreach \i  in {1,2,3,\pointslen-1}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}

%This gives the error 
%\texttt{! Illegal unit of measure (pt inserted).}
\begin{tikzpicture}
    \foreach \i  in {1,...,\numexpr\pointslen-1\relax}
        {\draw \points[\i] -- \points[\i+1];}
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

范围规范中的最后一项\foreach必须是整数。另外

\foreach \i in {1,...,5-1} {...}

会因相同的错误而失败。相反,\numexpr\pointslen-1\relax会起作用。

一种expl3实现方式:

\documentclass{article}
\usepackage{tikz}
\usepackage{xfp}

\ExplSyntaxOn
\NewDocumentCommand{\definelist}{mm}
 {
  \seq_clear_new:c { l_carlatex_list_#1_seq }
  \seq_set_split:cnn { l_carlatex_list_#1_seq } { ; } { #2 }
 }
\cs_generate_variant:Nn \seq_set_split:Nnn { c }

\NewExpandableDocumentCommand{\getlistitem}{mm}
 {
  \seq_item:cn { l_carlatex_list_#1_seq } { #2 }
 }
\NewExpandableDocumentCommand{\getlistlen}{m}
 {
  \seq_count:c { l_carlatex_list_#1_seq }
 }
\ExplSyntaxOff

\begin{document}
\definelist{points}{(1,2); (2,3); (3,2); (1,1); (2,2)}

This works:
\begin{tikzpicture}
  \foreach \i  in {1,...,\inteval{\getlistlen{points}-1}} {
    \draw \getlistitem{points}{\i} -- \getlistitem{points}{\i+1};
  }
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容