1

I implemented some commands/macros recently and I'm thinking about reducing the number of arguments given to a command/macro. Basically, until now I have created some macros with xparse or \cs_new:N from latex3. Here is an example:

\documentclass[a4paper]{article}

\ExplSyntaxOn

\NewDocumentCommand \foo {m}
{
    \str_new:N \l_my_word
    \str_set:Nn \l_my_word {#1}
    \twice{\l_my_word}

}

\cs_new:Npn \twice #1
{
    \str_use:N #1~\str_use:N #1
}

\ExplSyntaxOff

\begin{document} 
    \foo{Hello}
\end{document}

If I understand right, here the "l" from \l_my_word is just a naming convention. I could also write the command twice in the following way:

\cs_new:Npn \twice
{
    \str_use:N \l_my_word~\str_use:N \l_my_word
}

If I know I will use the variable \l_my_word in the command \twice do I have to use the first or the second version of the command ?

Thank you!

2 Answers 2

1

You word the question as if the second form is going against the convention but that is not so l_ prefix is the convention for names local to the current group (not to the current macro definition) so that is the case with both forms that you suggest as you used the local set command to define it.

So either form is fine, depending if you want to use \twice in other contexts.

2

There are a few weaknesses in your code.

The main one is that \str_new:N should not go in the definition of \foo, but outside. With your code, calling \foo twice would result in an error. Second, all names of variables should end with the variable type. Also, \twice should be an expl3 function.

Here's a possible implementation.

\documentclass[a4paper]{article}

\ExplSyntaxOn

\NewDocumentCommand \foo {m}
{
    \str_set:Nn \l_lucarmand_word_str {#1}
    \lucarmand_twice_str:N \l_lucarmand_word_str
}
\str_new:N \l_lucarmand_word_str

\cs_new:Npn \lucarmand_twice_str:N #1
{
    \str_use:N #1~\str_use:N #1
}

\ExplSyntaxOff

\begin{document}

\foo{Hello}

\end{document}

However, the same task can be accomplished without setting string variables and even become fully expandable.

\documentclass[a4paper]{article}

\ExplSyntaxOn

\NewExpandableDocumentCommand \foo {m}
 {
  \lucarmand_twice:e { \tl_to_str:n { #1 } }
 }

\cs_new:Nn \lucarmand_twice:n
 {
  #1~#1
 }
\cs_generate_variant:Nn \lucarmand_twice:n { e }

\ExplSyntaxOff

\begin{document} 

\foo{Hello}

\edef\test{\foo{Hello}}
\texttt{\meaning\test}

\end{document}

enter image description here

1
  • Thank you for pointing to the weaknesses of my code. I'll need time to fully understand your second implementation. I know there is an alternative, thank you!
    – Luc Armand
    Jun 11, 2021 at 17:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .