What are the basics of Lua strings?

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.

How to create a string in Lua

You can initialize strings in Lua in three ways:

  • Use single quotes
  • Use double quotes
  • Enclose text between [[ 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 sequences

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")

String manipulation

Lua has a number of built-in functions that allow the manipulation of strings. The most commonly used are as follows:

Method

Purpose

string.upper(argument)

Returns a capitalized representation of the argument.

string.lower(argument)

Returns a lower case representation of the argument.

string.gsub(stringToChange,findString,replaceString)

Returns a string by replacing occurrences of findString with replaceString. Additionally, it returns the count of total matches that took place.

string.reverse(argument)

Returns a reversed version of the string passed as argument.

string.len(argument)

Returns the length of the passed string.

String concatenation

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 string1
string1 = "lua strings tutorial"
--using string.upper() function to change string1
print(string.upper(string1))
-- using string.gsub() to replace a substring from string1
print(string.gsub(string1, "tutorial", "manipulation"))
--reversing string1 using string.reverse()
print(string.reverse(string1))
string2 = " has ended"
-- concatenating string1 and string2
print(string1..string2)

Free Resources