Strings


Words and other sequences of characters are represented by strings.

Lua strings are immutable, meaning that they cannot be modified after they are created. Changing a string requires creating a new string that consists of the characters of the previous string, plus whatever changes are desired. We will learn more about this when we look at string buffers in the Strings chapter.

Lua strings are defined by a sequence of characters contained in:

  1. Double quotes
  2. Single quotes
  3. Double square brackets

The characters of strings defined with either single or double quotes must exist on a single line, while those in strings defined with brackets can be on multiple lines. Strings defined with single and double quotes are equivalent, and both types of quotes are supported so that quote characters can be included in strings themselves.

print("this 'contains' quotes'")
print('this "also" contains quotes')

The following compares strings defined with quotes vs brackets:

-- single or double quotes
print("this is a string")
print("this is a\nmulti-line string")

-- square brackets
print([[this is a string]])
print([[this is a
multi-line string]])

Note that the quoted multi-line string definition included a \n at the point where the string broke between lines. This is called an escape character (sometimes also called an "escape sequence" or simply "escapes"), which is the topic of the next section.