Escape string for Lua string.format

I have a string, I need to add a variable, so I use the string.format method, but the string also contains the character "%20" (not sure if it represents, perhaps a space or something else). One way or another, since the line contains a few "%" , and I only want to add a variable to the first one to set the id, is there a way to avoid the line at points or something like that?

Like now:

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

I get the bad argument #3 to 'format' (no value). error bad argument #3 to 'format' (no value). - since he expects the transfer of three variables.

+6
source share
4 answers

You can escape % with another % , for example. string.format("%%20") will give %20

+5
source

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

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

In the code below, all URL escape sequences (i.e.% 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)) 
+1
source

I saw that you accepted the answer, but actually this situation almost never happens in a real application. You should try to avoid mixing patterns with other data.

If you have a line like this: x=foo=&bar=asd%20yolo%20123-1512 and you want to add part of the identifier 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 used %d because your identifier is a number, so in this case it is preferable to %s .)

+1
source

Source: https://habr.com/ru/post/951320/


All Articles