Escape string for Lua's string.format
Asked Answered
J

4

8

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.

Jinnah answered 8/8, 2013 at 13:36 Comment(0)
F
8

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

Fainthearted answered 8/8, 2013 at 13:38 Comment(1)
perfect, exactly what I was looking forJinnah
D
3

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

( ) . % + - * ? [ ] ^ $
Delanadelancey answered 8/8, 2013 at 14:4 Comment(0)
T
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))
Tricrotic answered 8/8, 2013 at 13:41 Comment(2)
Why %%%1 doesn't raise error? There are no captured substrings here. Only %%%0 is possible according to Lua manual.Karmakarmadharaya
@EgorSkriptunoff, the manual says "if the pattern specifies no captures, then it behaves as if the whole pattern was inside a capture.".Tricrotic
S
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.)

Schoen answered 8/8, 2013 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.