Q:

Using string.gsub to change x to y most efficiently (Lua)

I'm at a loss here, though I've been getting more and more familiar with gsub in Lua.  There probably is a better way to do this more efficiently, and that's what I'm looking for.  What I'm wishing to do is change:
\(port Planes)9e;\(enter pool)n2euw

into
port Planes;run 9e;enter pool;run n2euw

It seems like it would be a simple thing, but I'm totally drawing a blank.  I could probably attribute that partly to being exhausted, but that's not really an excuse.  The way I would have it is:
string.gsub(variable, ";","\(")
string.gsub(variable, "\(", ";")
string.gsub(variable, ")",";run")
string.gsub(variable, ";;",";")

But to me, that looks pretty sloppy, and not as efficient as I would like it to me.  It also poses the problem if ")" ends the line, and it'd put ";" there, which is not something I want.  I would appreciate the expertise of someone more familiar with Lua who can tidy this up and make it more efficient.  I'll be putting it into a function once all is said and done.  Thanks!
Edit: Upon testing that, it doesn't even work, anyway... and I can't figure out the proper pattern matching sequence to use to make it work at all...

A:

Without knowing more about the possible combinations you could have, I can't say that this would work in every instance but it should give a start:
string.gsub(variable,"\\%((.-)%)","%1;run ")
string.gsub(variable,";run $","")

The first gsub is returning the commands inside your parenthesis, removing the parenthesis and adding ';run ' at the end.
The second one is checking whether the end of the string is ';run ' and replacing it if that's the case.
You should also check out this article for a nice summary on patterns:
http://www.lua.org/pil/20.2.html

