← Back to Lua Course | Chapter 3: Strings | Lesson 1 of 7

String literals and escapes

Strings are written in quotes, and special characters are written with a backslash.

String literals and escapes

Strings can use single quotes, double quotes, or long brackets [[ ... ]] that span several lines and ignore escapes. Common escapes are \n for newline, \t for tab, \\ for a backslash and \" for a quote. Lua 5.3 also supports \x41 hexadecimal and \u{48} Unicode escapes. Strings are immutable, so operations always return new strings.

Note: Long brackets are perfect for multi-line text and can use levels like [==[ ... ]==] to contain ]].

Example: String literals and escapes

lua
print('single', "double")
print("tab:\there, quote: \"q\"")
print("hex \x41 and unicode \u{48}")
print([[long
string \n stays raw]])
print("a\\b")

-- Output:
-- single	double
-- tab:	here, quote: "q"
-- hex A and unicode H
-- long
-- string \n stays raw
-- a\b
Common Mistakes
  1. Forgetting to escape a quote inside the same kind of quotes
  2. Expecting escapes to work inside [[ ]]
  3. Trying to change a character in place
Chapter Summary
  • Use ' " or [[ ]]
  • \n \t \\ are common escapes
  • Long brackets ignore escapes
  • Strings are immutable

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.