我想在宏调用之间保存一个变量值,目的是不必在连续调用中重复大量参数。如果在文本模式下,一切都会按预期工作。如果我对每次调用单独调用数学模式,即$\myMacro$
,这就是我想要做的,则每次调用都会重置变量。有解决方法吗?
\documentclass{article}
\usepackage{xparse}
\usepackage{amsmath}
\ExplSyntaxOn
% VARIABLE DECLARATIONS:
\tl_new:N \savevar_rn_tl
\tl_set:Nn \savevar_rn_tl {INIT}
\NewDocumentCommand\myMacro{O{1}O{Z}}
{
!*\tl_use:N \savevar_rn_tl*! \\
\str_case:nn {#1}
{
{1}
{
#2\\
\tl_set:Nn \savevar_rn_tl {#2@#2}
}
{2}
{
\tl_use:N \savevar_rn_tl \\
\tl_set:Nn \savevar_rn_tl {RESET}
}
}
}
\ExplSyntaxOff
\begin{document}
\section{The way I want to use it, but savevar is not preserved between calls:}
$\myMacro$\\
$\myMacro[2]$\\
$\myMacro[1][\alpha]$\\
$\myMacro[2]$\\
\section{savevar is preserved between calls, but only if calls are made in textmode:}
\myMacro\\
\myMacro[2]\\
\myMacro[1][W]\\
\myMacro[2]\\
\end{document}
答案1
切换到数学模式会进入一个组,因此\tl_set:Nn
只能在组内设置值,而不能在组外设置值。如果要保留该值,则\tl_gset:Nn
必须使用(全局设置)。
表面上的‘重置’只是因为\savevar_rn_tl
外部仍然具有初始设置的值并且填充#2@#2
仅在本地、在组内。
\documentclass{article}
\usepackage{xparse}
\usepackage{amsmath}
\usepackage{mathtools}
\ExplSyntaxOn
% VARIABLE DECLARATIONS:
\tl_new:N \g_savevar_rn_tl
\tl_set:Nn \g_savevar_rn_tl {INIT}
\NewDocumentCommand\myMacro{O{1}O{Z}}
{
!*\tl_use:N \g_savevar_rn_tl*! \\
\str_case:nn {#1}
{
{1}
{
#2\\
Value\space before:\tl_use:N \g_savevar_rn_tl \\
\tl_gset:Nn \g_savevar_rn_tl {#2@#2}
Value\space after:\tl_use:N \g_savevar_rn_tl \\
}
{2}
{
Before: \tl_use:N \g_savevar_rn_tl \\
\tl_gset:Nn \g_savevar_rn_tl {RESET}
Value: \tl_use:N \g_savevar_rn_tl \\
}
}
}
\ExplSyntaxOff
\begin{document}
\section{The way I want to use it, but savevar is not preserved between calls:}
$\myMacro$\\
$\myMacro[2]$\\
$\myMacro[1][\alpha]$\\
$\myMacro[1][\beta]$
\section{savevar is preserved between calls, but only if calls are made in textmode:}
\ExplSyntaxOn
\tl_clear:N \g_savevar_rn_tl
\ExplSyntaxOff
\myMacro[1][A]\\
\myMacro[2]\\
\myMacro[1][W]\\
\myMacro[2]\\
\end{document}