Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

( ) . % + - * ? [ ] ^ $

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))

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.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top