Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape string for Lua's string.format

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.

like image 453
user1593846 Avatar asked Aug 08 '13 13:08

user1593846


People also ask

How do you escape a formatted string?

You can use a backslash to escape a formatting character: String. Format("{0:Save #\\%}", 100);

How do I escape characters in a string?

In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.

How do you escape a string in Lua?

Escaping a character means the character will be treated as part of the string, rather than a Lua instruction. To escape a character, place a \ in front of it, like so: message = "he said \"bye\" and left"print (message) ...

How do you escape a string in C #?

C# includes escaping character \ (backslash) before these special characters to include in a string. Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.


3 Answers

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

like image 187
dunc123 Avatar answered Sep 21 '22 07:09

dunc123


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

( ) . % + - * ? [ ] ^ $
like image 23
Yu Hao Avatar answered Sep 22 '22 07:09

Yu Hao


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))
like image 24
lhf Avatar answered Sep 22 '22 07:09

lhf