12

The minimal example below should replace all # characters with another symbol. This works well if I use \# to escape it, but the user should later be able to enter it directly, e.g. to enter hash tags.

I understand that # is a special character, but I'd like a solution without tinkering with character classes and patching macros (we need it # as special character at the same time to get the parameter value).

FYI: The overall goal of this is a package to create "Share on Twitter" links.

\documentclass{minimal}

\usepackage{luacode}

\newcommand{\Test}[1]{
    \luaexec{
        local x = string.gsub("#1", "\#", "+")
        tex.print(x)
    }
}

\begin{document}
\Test{With backslash: \#} % Yields "Wit backslash: +"

\Test{Without backslash: #} % Yields "Without backslash: + +"
\end{document}
13

You should be writing ## not \# in your macro:

Sample output

\documentclass{minimal}

\usepackage{luacode}

\newcommand{\Test}[1]{
    \luaexec{
        local x = string.gsub("#1", "##", "+")
        tex.print(x)
    }
}

\begin{document}
\Test{With backslash: \#} % Throws an error as # is not processable in output

\Test{Without backslash: #} % 
\end{document}
  • Thanks for your answer :-) It is still not completely clear to me why # is expanded to ## by TeX, but it works. For most other special characters I can work with \@makeother. – Marcus Bitzl Dec 11 '13 at 13:35
  • This is the standard behaviour of tex in macros, # is escaped as ## so as not be confused with parameters #1 etc. See tex.stackexchange.com/q/42463/15925 – Andrew Swann Dec 11 '13 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.