使用键时 .choices 的正确用法是什么?

使用键时 .choices 的正确用法是什么?

我尝试normanius以以下方式创建一个键:每个键都映射到一个自己的变量\l__normanius_*_tl,以便我可以在某些后续代码中使用这些变量。

\documentclass{article}
\usepackage{expl3}
\begin{document}
\ExplSyntaxOn
\keys_define:nn { normanius }
 {
   one .bool_set:N = \l__normanius_one_bool,
   one .initial:n = { false },
   
   two .tl_set:N = \l__normanius_two_tl,
   two .initial:n = { anything },
   
   three .tl_set:N = \l__normanius_three_tl,
   three .initial:n = { foo },
   three .choices:nn = { foo, bar } { }

 }
 
\NewDocumentCommand{\test}{m}{
  \keys_set:nn { normanius }{ #1 }
  \bool_if:NTF\l__normanius_one_bool
   { (yes,~\l__normanius_two_tl,~\l__normanius_three_tl) }
   { (no,~\l__normanius_two_tl,~\l__normanius_three_tl) } 
  
}

\ExplSyntaxOff

\test{}

\test{one=true, three=bar}    % No error, but choice is not set
%\test{one=true, three=ohoh}  % Error, choice is checked
\end{document}

以上创建此输出:

(no, anything, foo)
(yes, anything, foo)

但是,它应该(yes, anything, bar)在第二行。选择被选中,\test{one=true, three=ohoh}会发出错误。但是,l__normanius_three_tl永远不会更新。

我这里哪里出错了?为什么l__normanius_three_tl设置不正确?

答案1

根据上述讨论的建议,我找到了一个可行的解决方案。下面的示例代码说明了如何使用带有选择的键。

在这里使用组非常重要,否则键的初始化无法正常工作。

一个重要的资源是LaTeX3 / l3kernel的接口文档,参见这里

\documentclass{article}
\usepackage{expl3}


\ExplSyntaxOn
% Declare variables. Not exactly needed in this example, 
% but recommended.
\bool_new:N \l__normanius_one_bool
\tl_new:N \l__normanius_two_bool
\tl_new:N \l__normanius_three_bool
\tl_new:N \l__normanius_four_bool

% Define keys with accessor variables, and default settings.
\keys_define:nn { normanius }
 {
   one .bool_set:N = \l__normanius_one_bool,
   one .initial:n = { false },
   
   two .tl_set:N = \l__normanius_two_tl,
   two .initial:n = { anything },
   
   three .tl_set:N = \l__normanius_three_tl,
   three .initial:n = { foo },
   three .choices:nn = { foo, bar } { \tl_set:Nn \l__normanius_three_tl {#1} },
   
   four .tl_set:N = \l__normanius_four_tl,
   four .initial:n = { A1 },
   four .choices:nn = { A1, A2, A3 } { \tl_set:Nn \l__normanius_four_tl {#1} },
 }
 
% Some function that makes use of the keys.
\NewDocumentCommand{\test}{m}{
  % Use groups to ensure local assignments. Ensures that the default 
  % values are reinitialized each time this command is called!
  \group_begin:
  \keys_set:nn { normanius }{ #1 }
  \bool_if:NTF\l__normanius_one_bool
   { (yes,~\l__normanius_two_tl,~\l__normanius_three_tl,~\l__normanius_four_tl) }
   { (no,~\l__normanius_two_tl,~\l__normanius_three_tl,~\l__normanius_four_tl) } 
  \group_end:
}
\ExplSyntaxOff


\begin{document}
\noindent
\test{}\\
\test{one=true, three=bar}\\
\test{one=true, three=bar}\\
\test{three=bar, three=foo}\\
\test{three=bar, four=A2}\\
%\test{one=true, three=ohoh}  % Error! 
\end{document}

这将创建以下输出:

(no, anything, foo, A1)
(yes, anything, bar, A1)
(yes, anything, bar, A1)
(no, anything, foo, A1)
(no, something, foo, A1)
(no, anything, bar, A2)

相关内容