\int_incr:N 在表格環境中

\int_incr:N 在表格環境中

我幾週前開始學習 LaTeX3,目前正在擺弄表格。這是我的程式碼:

\documentclass{article}
\usepackage{expl3}

\ExplSyntaxOn
\cs_new_protected:Npn \juhu_tablerow:n #1
{
  \int_new:N \l_row_count_int
  \int_set:Nn \l_row_count_int { 1 }
  \prg_replicate:nn {#1}
  {
    \int_use:N \l_row_count_int .~row \\
    \int_incr:N \l_row_count_int
  }
}
\cs_new_eq:NN \tablerow \juhu_tablerow:n
\ExplSyntaxOff

\begin{document}

\begin{tabular}{c}
\tablerow{3}
\end{tabular}

\end{document}

這段程式碼的輸出是:

1. row
1. row
1. row

期望的輸出應該是這樣的:

1. row
2. row
3. row

當我用tabular環境替換環境例如時center,我得到了預期的輸出。

現在,如果我將\\in替換\int_use:N \l_row_count_int .~row \\,~,\int_incr:N似乎即使在tabular環境內部也能再次工作,輸出為:

1. row, 2. row, 3. row, 

所以,我的問題是,為什麼在使用多行時增加整數在環境中不起作用tabular,我該怎麼做才能獲得所需的結果?

答案1

從我的謙虛評論到答案。:)

您已經非常接近解決方案了!這裡的罪魁禍首是範圍:這些分配是在本地發生的;讓我們讓它們全球化。

在繼續之前,我們必須將整數聲明移到命令定義之外,否則在後續調用\tablerow.現在,有一點編碼約定,來自

\int_new:N \l_row_count_int

\int_new:N \g_row_count_int

自從我們的櫃檯變得全球化以來。:)現在,有幾個替代品(感謝egreg的建議xparse!):

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\int_new:N \g_row_count_int

\cs_new_protected:Npn \juhu_tablerow:n #1
{
  \int_gset:Nn \g_row_count_int { 1 }
  \prg_replicate:nn {#1}
  {
    \int_use:N \g_row_count_int .~row \\
    \int_gincr:N \g_row_count_int
  }
}

\NewDocumentCommand{ \tablerow }{ m }{
    \juhu_tablerow:n{#1}
}
\ExplSyntaxOff

\begin{document}

\begin{tabular}{c}
\tablerow{3}
\end{tabular}

\end{document}

一切都應該工作得很好。:)

您也可以使用\g_tmpa_intwhich is 一個臨時整數進行全域分配,這樣可以節省一些錢。:)

相關內容