Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add double quote characters to a string?

Tags:

lua

How can I add double quote characters to a given string?

local str = "foo"

How can I get the string "foo" where the string contains a leading and trailing quote "?

like image 465
che Avatar asked Mar 14 '11 22:03

che


1 Answers

You can just glue the quote to the string:

local str = "foo"

print('"' .. foo .. '"') --> "foo"
print("\"" .. foo .. "\"") --> "foo"
print([["]] .. foo .. [["]]) --> "foo"

But if you're constructing data for machine consumption (e.g. for serialization), you want to escape quotes and other funny characters that may be inside the string. Use "%q" format specifier for this:

local str = 'f"o"o'

print(string.format("%q", str)) --> "f\"o\"o"

In shorter form:

print(("%q"):format(str)) --> "f\"o\"o"
like image 152
Alexander Gladysh Avatar answered Sep 21 '22 21:09

Alexander Gladysh