Lua Strings
Published Aug 9, 2023
Contribute to Docs
Strings are a sequence of characters of any length that can include letters, numbers, symbols, and spaces.
Syntax
In Lua, a string is a sequence of characters surrounded by a pair of single quotes '' or double quotes "".
location = "Central Park" -- "Central Park" is a string
Concatenation
Multiple strings can be combined together using the concatenation operator ...
time = 10location = "Central Park"print("We will arrive at " .. location .. " at ".. time)
Escape Characters
Escape characters are used for clarity and conciseness. Sometimes, Lua may interpret a character in a string, which can cause errors. To avoid this, escape characters can be used to clarify that a character should be read as a string.
brokenString = "They said, "Hello!"" -- This will cause "Hello!" to be outside of the stringrevisedString = "They said, \"Hello!\"" -- This will keep "Hello!" inside of the string using escape characters
The following is a list of some useful escape characters supported by Lua strings:
| Description | Escape Characters |
|---|---|
| bell | \a |
| backspace | \b |
| form feed | \f |
| new line | \n |
| carriage return | \r |
| horizontal tab | \t |
| vertical tab | \v |
| backslash | \\ |
| quotation mark [double quote] | \" |
| apostrophe [single quote] | \' |
String Functions
Lua’s string library contains many different string functions that can be used to manipulate strings. These functions include the following:
Strings
- .byte()
- Returns the ASCII equivalent of a given character.
- .char()
- Converts a decimal value to its character representation.
- .find()
- Used to search for a substring (pattern) within a given string
- .format()
- Creates formatted strings.
- .len()
- Returns the length of a string, measured in bytes.
- .lower()
- Returns a copy of the string given, with all uppercase characters transformed to lowercase.
- .reverse()
- Returns a provided string in reverse order.
- .sub()
- Extracts a substring from a given string.
- .upper()
- Converts all letters in a string to uppercase.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
- Beginner Friendly.4 hours