无限循环、csname 和 forloop 函数

无限循环、csname 和 forloop 函数

我想定义一些以“a”、“b”、“c”结尾的命令...并计算它们的数量总和,我该怎么做??

\documentclass{article} \usepackage[utf8]{inputenc}

\usepackage{ifthen} 
\usepackage{pgffor} 
\usepackage{alphalph}
\usepackage{etoolbox} 
\usepackage{forloop}

\newcounter{totpecas}

\newcommand \peca {This is the first.} 
\newcommand \pecab {This is the
 second.} 
\newcommand \pecac {This is the third.}
\newcommand \npecatot{1}

\begin{document}

 \forloop{totpecas}{2}{{\ifcsdef{peca\alphalph{\value{totpecas}}}{1}{0}}
 = 1}{\renewcommand \npecatot {\value{totpecas}}}

 The number of defined commands is {\npecatot}.\\

\end{document}

答案1

这是 OP 设置的一个“小”变化,其中对 的测试\forloop不是用 完成的\ifcsdef(最有可能由于设置不同而失败)而是检查其他计数器值是否具有 的值1

必须重新定义该命令并且必须在定义中扩展计数器\npecatot的值。totpeca

\documentclass{article} \usepackage[utf8]{inputenc}

\usepackage{alphalph}
\usepackage{forloop}


\newcounter{totpecas}
\newcounter{notfound}

\newcommand\pecaa{This is the first.} 
\newcommand\pecab{This is the  second.} 
\newcommand\pecac{This is the third.}
\newcommand\pecad{This is the fourth.} 
\newcommand\pecae{This is the  fifth.} 
\newcommand\pecaf{This is the sixth.}

\newcommand\npecatot{1}

\begin{document}

\makeatletter


\forloop{totpecas}{1}{\value{notfound} < 1}{%
  \@ifundefined{peca\alphalph{\value{totpecas}}}{%
    \setcounter{notfound}{1}%
  }{%
    \expandafter\renewcommand\expandafter{\expandafter\npecatot\expandafter}\expandafter{\number\value{totpecas}}%
  }%
}
\makeatother


The number of defined commands is \npecatot.


\end{document}

在此处输入图片描述

答案2

更少的包,带有“while”循环。

\documentclass{article}

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\computepecatot}{s}
 {
  \int_set:Nn \l_sara_peca_count_int { 1 }
  \bool_do_while:nn
   {
    \cs_if_exist_p:c { peca\int_to_alph:n { \l_sara_peca_count_int } }
   }
   {
    \int_incr:N \l_sara_peca_count_int
   }
  \int_decr:N \l_sara_peca_count_int
  \IfBooleanT{#1}
   {
    \npecatot
   }
 }
\NewExpandableDocumentCommand{\npecatot}{}
 {
  \int_to_arabic:n { \l_sara_peca_count_int }
 }
\int_new:N \l_sara_peca_count_int
\ExplSyntaxOff

\newcommand \pecaa {This is the first.} 
\newcommand \pecab {This is the second.} 
\newcommand \pecac {This is the third.}

\begin{document}

The number of \texttt{peca} commands is \computepecatot*.

\newcommand{\pecad}{Fourth}

\computepecatot

The number of \texttt{peca} commands is \npecatot.

\ExplSyntaxOn
\int_step_inline:nnnn { 5 } { 1 } { 99 }
 {
  \cs_new:cpn { peca\int_to_alph:n { #1 } } { Whatever }
 }
\ExplSyntaxOff

Now it is \computepecatot*.

\end{document}

在此处输入图片描述

相关内容