Lua issues with string containing double and/or single quotes - string.format("%q") suffixes with \13

Viewed 343

In lua, I'm reading a text file, which lines may contain single or double quotes such as: "L'habitude commence comme un fil de soie et devient vite un câble d'acier" - Proverbe espagnol

the lines are used as such:

local cmd = 'zenity --question --no-wrap  --title "pause" --text ' .. string.format("%q", quote)
print (cmd)
local retVal = os.execute(cmd)

Everything works fine, but at the very end of string there the character \13 is suffixed to the string, which I do not want.

zenity --question --no-wrap --title "pause" --text "L'habitude commence comme un fil de soie et devient vite un câble d'acier. - Proverbe espagnol\13"

And zenity windows displays this \13 char.

How to solve this?

Thanks

Related: How to add double quote characters to a string?

2 Answers

Your quote contains a carriage return. Carriage return is not a printable character. How should Lua quote a non-printable character?

From the Lua 5.4 Reference Manual: string.format

The specifier q formats booleans, nil, numbers, and strings in a way that the result is a valid constant in Lua source code. Booleans and nil are written in the obvious way (true, false, nil). Floats are written in hexadecimal, to preserve full precision. A string is written between double quotes, using escape sequences when necessary to ensure that it can safely be read back by the Lua interpreter. For instance, the call

 string.format('%q', 'a string with "quotes" and \n new line')

may produce the string:

 "a string with \"quotes\" and \
  new line"

Remove it if you don't want it to end up in your string as \13.

You can use string.sub to remove it. Multiple carriage returns are best removed using string.gsub.

Alternatively use string.format('"%s"', quote) or string.format("\"%s\"", quote). There's even more ways to write double quotes in a string.

Your original text ended with \13, a CR. Remove it with

quote = quote:sub(quote,1,-2)

If the string might not end with a CR, then remove it if present with

quote = quote:gsub("\13$","")
Related