13

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}

1 Answer 1

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}
2
  • 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. Commented Dec 11, 2013 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 Commented Dec 11, 2013 at 13:45

You must log in to answer this question.

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