Get string in double quotes in lua

if the string is passed to the lua function How to get this string in a double quote string

like somestring is a string passed to the XYZ function in lua you need the value of somestring in double quotes.

+3
source share
3 answers

If I understood your question, you can do this in several ways.

  • Use a hidden double quote:

    function quote(str)
        return "\""..str.."\""
    end
    
  • Use a single quote to use the double quote character without escaping:

    function quote2(str)
        return '"'..str..'"'
    end
    
+4
source

You can simply stick the quote to the line:

local str = "foo"

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

(, ), , . "%q":

local str = 'f"o"o'

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

:

print(("%q"):format(str)) --> "f\"o\"o"
+5

Just in case, you would like to run away and quote:

function string.quote(str)
  return '"' .. str:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"'
end

local a = '"Hello again \\ to all my friends"'

print(a:quote())

Which will give you the following line:

"\"Hello again \\ to all my friends\""
0
source

All Articles