Lua strings: escape a backslash

How to put a literal backslash in a Lua string: doubling it in quoted strings, using long brackets, version differences, patterns, %q, and why escaped text breaks when copied between tools.

In a quoted Lua string, the backslash starts an escape sequence. To get one literal backslash, you write two. The alternative is a long-bracket string, which does no escape processing at all. This review explains what each form changes, which one suits which job, and where backslashes get lost when code moves between tools.

The short answer

local a = "C:\\Temp\\logs"   -- quoted: double each backslash
local b = [[C:\Temp\logs]]   -- long bracket: written as-is
print(a)        --> C:\Temp\logs
print(a == b)   --> true
print(#"\\")    --> 1

What escaping actually changes

Escaping changes only how the string is written in source code. When Lua reads the literal "\", it stores a single backslash byte. The runtime value has one backslash, which is why the length of "\" is 1. The doubled form exists only in the source file. This is not a visual or presentational change like a mirrored or restyled 'font'. Once parsed, the stored characters are exactly the ones you intended, provided the escaping was written correctly.

Doubling is necessary because the backslash introduces other sequences. A lone backslash followed by a letter, digit or quote is read as an instruction, not as a character. The sequences recognized by the reference implementation are:

  • \ produces one backslash
  • " and ' produce a quote character inside a string delimited by that quote
  • \n, \t, \r, \a, \b, \f and \v produce control characters
  • \ddd produces the byte given by up to three decimal digits, so \92 is also a backslash
  • \xXX produces a byte given in hexadecimal (Lua 5.2 and later)
  • \z skips the following whitespace, including line breaks (Lua 5.2 and later)
  • \u{XXX} produces the UTF-8 encoding of a code point (Lua 5.3 and later)
  • A backslash followed by an actual line break produces a newline in the string

How a single backslash breaks a string

"C:\Temp"     -- \T is not an escape: error in 5.2+, "C:Temp" in 5.1
"C:\new\test" -- valid escapes: newline and tab, no error
"C:\dir\"     -- \" escapes the quote: unfinished string

There are three distinct failure modes. First, an unrecognized escape such as \T is rejected at compile time with an invalid escape sequence error in Lua 5.2 and later. Lua 5.1's reference implementation is lenient and drops the backslash, so the path silently becomes C:Temp. Second, a single backslash that happens to form a valid escape is the most dangerous case. In "C:\new\test", \n becomes a newline and \t becomes a tab, and no Lua version raises an error. Third, a trailing single backslash escapes the closing quote, so the literal never ends and the parser reports an unfinished string. LuaJIT and embedded Lua variants are not covered by this description; check their behavior against your own runtime.

Long brackets: no escaping at all

local path = [[C:\Program Files\App\]]
local text = [==[contains ]] and \d as typed]==]
print(path)  --> C:\Program Files\App\

Text between [[ and ]] is taken literally, so backslashes need no doubling. A trailing backslash is also fine. If the content itself contains ]], add equal signs to the brackets, as in [==[ ... ]==]. The closing bracket must use the same number of equal signs. A line break immediately after the opening bracket is dropped. Any end-of-line sequence inside the string is normalized to a plain newline.

The tradeoff is that no escapes work inside long brackets. \n, \t, \x and \u{} all stay as literal text. A control character must therefore be typed as the actual character, or concatenated from a quoted string.

Choosing between the forms

Situation | Recommended form | Reason
Short path or one-off literal | Quoted, with doubled backslashes | Stays on one line and can mix with \n and other escapes
Many backslashes (Windows paths, LaTeX, regex for external tools) | Long bracket | Reads exactly as typed and is easier to verify
Also needs control characters or byte escapes | Quoted, with escapes | Long brackets cannot express escapes
Code generated by a program | string.format("%q", s) | Lua produces a literal it can read back
Value ends with a backslash | "dir\" or [[dir]] | A single trailing backslash in quotes breaks the literal

Backslashes in Lua patterns

Lua patterns in string.find, string.match, string.gmatch and string.gsub use the percent sign as their escape character, not the backslash. A backslash therefore has no special meaning inside a pattern. Only the string-literal layer applies. To match one backslash, the pattern is "\", which is a single character at runtime. Many regex engines in other languages would require four backslashes here. For the same reason, "\d" is not a digit class in Lua; the digit class is %d. Replacement strings in gsub also treat percent, not backslash, as special.

local s = [[C:\Temp\logs]]
print((s:gsub("\\", "/")))      --> C:/Temp/logs
print(s:find("\\", 1, true))    --> 3  3

Generating escaped strings with %q

string.format("%q", s) returns a quoted literal that Lua can read back. It doubles backslashes, escapes double quotes and writes a newline as a backslash followed by a line break. Use it for code generation and simple serialization. The output is meant for a Lua parser, not for display or for other languages. Its handling of other control characters differs between Lua versions, so test it on your runtime.

local s = [[C:\Temp]] .. "\n" .. 'say "hi"'
print(string.format("%q", s))
-- prints:
-- "C:\\Temp\
-- say \"hi\""

Will it survive copying and sharing?

A doubled backslash means 'one backslash' only to the Lua parser. Every other layer with its own escaping rules adds another round. This includes JSON, C string literals, shell double quotes and other languages' strings. Lua code stored as a JSON string value needs each backslash doubled again. POSIX shell single quotes pass backslashes through unchanged.

-- Lua source
print("C:\\Temp")

-- Same code as a JSON string value
"print(\"C:\\\\Temp\")"

-- Same code passed to a POSIX shell in single quotes
lua -e 'print("C:\\Temp")'

The reverse direction causes errors too. Copying a printed runtime value, which has single backslashes, into a quoted literal requires re-doubling. So does moving text from a long-bracket string into a quoted one. Outside code blocks, CommonMark Markdown treats a backslash before punctuation as an escape. A snippet pasted as plain prose can therefore lose a backslash when rendered, so keep snippets in code blocks. Word processors that convert straight quotes to curly quotes will also break a literal.

Searching and editing need the same care. A search for C:\Temp will not match the source text C:\Temp. Tools like grep treat the backslash as their own escape character, so a fixed-string mode such as grep -F avoids a further layer. A form with fewer backslashes, such as a long bracket or a single named constant, is easier for any reader or reviewer to check. How a specific screen reader announces runs of backslashes depends on the product and its punctuation settings. That was not tested here.

Evaluating an 'escape for Lua' tool

A string-escaping tool aimed at Lua should do four things: double every backslash, escape the quote character that delimits the string, and handle control characters. It should also state which Lua version it targets, because \x, \z and \u{} output will not parse on Lua 5.1. The simplest check is a round trip. Paste the tool's output into a literal and compare it with == against the original read from a file. No specific online tool was evaluated for this article. A tool's privacy or data-retention practices cannot be judged from its appearance, so avoid pasting secrets or credentials into web-based escapers.

Verdict

For a short literal, doubling the backslash is correct and preserves the value exactly. For backslash-heavy text, long brackets are more readable and less error-prone, at the cost of losing escapes. For generated code, %q is the safest option. The decisive tradeoff is that escaping is specific to each layer: it is correct for the Lua parser and wrong for any other layer the text passes through. Plain, unescaped text is preferable when the value can live outside source code, for example in a configuration file or input read at runtime. Lua does not process backslashes in data read from files.

Limits of this review: the behavior described comes from the Lua reference manual and the reference implementation. No version-by-version test results or tool measurements were available. Behavior in LuaJIT, Luau and other embedded variants should be confirmed in the environment you deploy to.