![動態表格:設定表格後的列號](https://rvso.com/image/420037/%E5%8B%95%E6%85%8B%E8%A1%A8%E6%A0%BC%EF%BC%9A%E8%A8%AD%E5%AE%9A%E8%A1%A8%E6%A0%BC%E5%BE%8C%E7%9A%84%E5%88%97%E8%99%9F.png)
我想建立一個動態表格,\N
在頁面開頭有一個列,其中\N
是整個文件的節數,因此\N
設定的值後桌子。當我設定\N
table 之前的值時(在我的範例中,將 line 26 移到\N=\value{section}
line 10 之後\section{section 1}
),一切正常,但是當我設定 table 之後的值時\N
(如我的範例所示),這會生成錯誤。
\N
這是我的程式碼,表後面有 set 的值。我想這並不難,但我找不到解決方案。有人有想法嗎?
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}
\newtoks\cols
\newcounter{i}
\newcount\N
\begin{document}
\section{section 1}
\cols={}
\setcounter{i}{1}
\loop
\cols=\expandafter{\the\expandafter\cols\the\value{i}}
\ifnum\value{i}<\N
\cols=\expandafter{\the\cols &}
\stepcounter{i}
\repeat
\begin{tabular}{|*{\N}{c|}}
\the\cols
\end{tabular}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}
\N=\value{section}
\end{document}
答案1
通常,可以透過將表儲存到外部文件在文件末尾。您所需要做的就是\input
文件前面部分的外部文件。然而,這確實需要編譯文件兩次才能正確更新表。這是一個例子:
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}
\usepackage{expl3}
\begin{document}
\section{section 1}
% load the table, if it exists
\InputIfFileExists{\jobname.table}{}{}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}
\ExplSyntaxOn
% open external file for writing
\iow_open:Nn \g_tmpa_iow {\jobname.table}
% get number of sections
\int_set:Nn \l_tmpa_int {\value{section}}
% write begin environment
\iow_now:Nx \g_tmpa_iow {\c_backslash_str begin{tabular}
{|*{\int_use:N \l_tmpa_int}{c|}}}
% write columns into a sequence
\seq_clear:N \l_tmpa_seq
% loop over integers and fill the sequence
\int_step_inline:nn {\l_tmpa_int} {
\seq_put_right:Nn \l_tmpa_seq {#1}
}
% write table content
\iow_now:Nx \g_tmpa_iow {
\seq_use:Nn \l_tmpa_seq {~&~} % join the sequence with " & "
}
% write end environment
\iow_now:Nx \g_tmpa_iow {\c_backslash_str end{tabular}}
\iow_close:N \g_tmpa_iow
\ExplSyntaxOff
\end{document}
我對LaTeX3比較熟悉。我相信您也可以使用 LaTeX2e 程式碼來實現相同的目標。
更新:將節數儲存在變數中
如果您只想將節數儲存在變數中,這裡有一個更簡單的範例。它將該行寫入文件\global\def\numsection{5}
,aux
可以在下次運行時存取該文件。
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{graphicx}
\begin{document}
Number of sections: \numsection
\section{section 1}
\section{section 2}
\section{section 3}
\section{section 4}
\section{section 5}
\makeatletter
\immediate\write\@auxout{\string\global\string\def\string\numsection{\the\value{section}}}
\makeatother
\end{document}