我想使用 创建一个简单的地图\newcommand
。我的\NewMapItem
命令定义了另一个返回项目值的命令。\MapItem
只需替换该命令即可。
\documentclass{article}
\newcommand{\NewMapItem}[2]{\newcommand{\Map@#1}{#2}}
\newcommand{\MapItem}[1]{\Map@#1}
\begin{document}
\NewMapItem{Canberk}{Qwerty}
\MapItem{Canberk}
\end{document}
但它不起作用。输出为:
line 5: Missing number, treated as zero. \NewMapItem{Canberk}{Qwerty}
line 5: You already have nine parameters. \NewMapItem{Canberk}{Qwerty}
你能解释一下吗?
答案1
看Latex 动态宏定义对于\NewMapItem
问题,以及如何知道我们是否需要 \expandafter?就此事进行讨论。
\newcommand{\NewMapItem}[2]{%
\expandafter\newcommand\csname Map@#1\endcsname{#2}}
\newcommand{\MapItem}[1]{\csname Map@#1\endcsname}
除非使用 ,否则您无法以此方式形成令牌\csname
。
一个不同的解决方案expl3
:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
% allocate a global property list
\prop_new:N \g_jnbrq_maps_prop
% the user level command for adding properties
\NewDocumentCommand{\NewMapItem}{mm}
{
\prop_gput:Nnn \g_jnbrq_maps_prop { #1 } { #2 }
}
% the user level command for retrieving a property
\DeclareExpandableDocumentCommand{\MapItem}{m}
{
\prop_item:Nn \g_jnbrq_maps_prop { #1 }
}
\ExplSyntaxOff
\begin{document}
\NewMapItem{Canberk}{Qwerty}
\MapItem{Canberk}
\end{document}
可以检查该属性是否已经存在:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
% allocate a global property list
\prop_new:N \g_jnbrq_maps_prop
% an error message for duplicate property
\msg_new:nnnn { jnbrq/maps } { duplicate-property }
{
Already~existing~property~#1
}
{
Property~#1~is~already~defined,~I'm~ignoring~
this~redefinition
}
% the user level command for adding properties
\NewDocumentCommand{\NewMapItem}{mm}
{
\prop_if_in:NnTF \g_jnbrq_maps_prop { #1 }
{
\msg_error:nnn { jnbrq/maps } { duplicate-property } { #1 }
}
{
\prop_gput:Nnn \g_jnbrq_maps_prop { #1 } { #2 }
}
}
% the user level command for retrieving a property
\DeclareExpandableDocumentCommand{\MapItem}{m}
{
\prop_item:Nn \g_jnbrq_maps_prop { #1 }
}
\ExplSyntaxOff
\begin{document}
\NewMapItem{Canberk}{Qwerty}
\NewMapItem{Canberk}{QQQ}
\MapItem{Canberk}
\end{document}
这将引发错误
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! jnbrq/maps error: "duplicate-property"
!
! Already existing property Canberk
!
! See the jnbrq/maps documentation for further information.
!
! For immediate help type H <return>.
!...............................................
l.37 \NewMapItem{Canberk}{QQQ}
? h
|'''''''''''''''''''''''''''''''''''''''''''''''
| Property Canberk is already defined, I'm ignoring this redefinition
|...............................................
这将比 发出的标准错误更容易理解\newcommand
。