Strings are sequences of characters that store letters, numbers, symbols, and even whole sentences.
Strings in Lua are immutable, which means that they can’t be changed once declared. However, Lua does provide ways to modify strings, which we will discuss below.
You can initialize strings in Lua in three ways:
[[
and ]]
The code below demonstrates how to use the three methods of initialization:
string1 = 'Lua string'print('string1 is', string1)string2 = "This is another Lua string"print("string2 is", string2)string3 = [["I'm the last Lua string"]]print("String3 is", string3)
Escape sequence characters are commonly used to modify simple strings. The different escape sequence characters and their usages are listed below:
Escape sequence | Usage |
---|---|
\n | Newline |
\b | Backspace |
\t | Horizontal tab |
\a | Bell |
\f | Form feed |
\r | Carriage return |
\v | Vertical tab |
\\ | Backslash |
\" | Double quote |
\’ | Single quote |
\[ | Left square bracket |
\] | Right square bracket |
Let’s look at a few examples to illustrate the use of escape sequences:
print("\'in single quotes\', \"in double quotes\"")print("This is line 1\nThis is line 2")print("Sentence with \ta lot \t\t of \t\t\t spaces")
Lua has a number of built-in functions that allow the manipulation of strings. The most commonly used are as follows:
Method | Purpose |
| Returns a capitalized representation of the argument. |
| Returns a lower case representation of the argument. |
| Returns a string by replacing occurrences of |
| Returns a reversed version of the string passed as argument. |
| Returns the length of the passed string. |
Besides manipulating a string, Lua also allows you to use ..
(known as concatenation operator) to concatenate or join two strings.
Let’s look at some examples of string manipulation and concatenation.
-- initializing string1string1 = "lua strings tutorial"--using string.upper() function to change string1print(string.upper(string1))-- using string.gsub() to replace a substring from string1print(string.gsub(string1, "tutorial", "manipulation"))--reversing string1 using string.reverse()print(string.reverse(string1))string2 = " has ended"-- concatenating string1 and string2print(string1..string2)