7

I have a string I need to add a variable to so I use the string.format method, but the string also contains the symbol "%20" (not sure what it represents, probably a white space or something). Anyway since the string contains multiple "%" and I only want to add the variable to the first one to set the id, is there a way to escape the string at the points or something?

As it is now:

ID = 12345
string.format("id=%s&x=foo=&bar=asd%20yolo%20123-1512", ID)

I get bad argument #3 to 'format' (no value). error -- since it expects 3 variables to be passed.

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
user1593846
  • 734
  • 1
  • 15
  • 34

4 Answers4

6

You can escape a % with another %, e.g. string.format("%%20") will give %20

greatwolf
  • 20,287
  • 13
  • 71
  • 105
dunc123
  • 2,595
  • 1
  • 11
  • 11
3

Unlike many other languages, Lua uses % to escape the following magic characters:

( ) . % + - * ? [ ] ^ $
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1

The code below escape all URL escapes (that is, % followed by a digit):

ID=12345
f="id=%s&x=foo=&bar=asd%20yolo%20123-1512"
f=f:gsub("%%%d","%%%1")
print(string.format(f,ID))
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Why `%%%1` doesn't raise error? There are no captured substrings here. Only `%%%0` is possible according to Lua manual. – Egor Skriptunoff Aug 08 '13 at 16:51
  • 2
    @EgorSkriptunoff, the manual says "if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.". – lhf Aug 08 '13 at 17:45
1

I have seen you have accepted an answer, but really, this situation should almost never happen in a real application. You should try to avoid mixing patterns with other data.

If you have a string like this: x=foo=&bar=asd%20yolo%20123-1512 and you want to prepend the ID part to it using string.format, you should use something like this:

s = "x=foo=&bar=asd%20yolo%20123-1512"
ID = 12345
string.format("id=%d&%s", ID, s)

(Note: I have used %d because your ID is a number, so it is prefered to %s in this case.)

catwell
  • 6,770
  • 1
  • 23
  • 21