I have never tried to include Lua code in a document before so please be gentle. I am after a pattern matching expression that will eventually take (stuff1)->(stuff2) and replace it with !(stuff1)||(stuff2) but baby steps first...
At the bottom of this page: Programming In Lua is a mention of a pattern for matching balanced strings. After modifying some code I found on site I decided to try the following:
\documentclass{article}
\def\swap#1{%
\directlua{%
local s, _ = string.gsub("#1","%b()%b()","%2%1")
tex.sprint(s)}
}
\begin{document}
\swap{(a)(b)}
\end{document}
Which does not work at all. Can anyone explain what I've done wrong?

luacodepackage as well. – Scott H. Sep 15 '12 at 00:49\string\%is an easier way to get a percent character in a Lua string (it will be escaped by a backslash), so\swapgsubargscould be replaced by"(\string\%b())(\string\%b())","\string\%2\string\%1", avoiding any catcode change. – Bruno Le Floch Sep 03 '14 at 12:00\string\%depends on the correct setting of\escapechar. Another alternative is LaTeX's\@percentchar. – Heiko Oberdiek Sep 03 '14 at 16:17