Understanding Lua Strings

In this article, we will explore Lua strings, their properties, operations, and usage with examples.

Strings are an important data type in programming that represent a sequence of characters. They are widely used for storing and manipulating textual data.

In Lua, strings can be created using single quotes(), double quotes() or square brackets (string is placed between [[ and ]]).

Lua Strings Properties

Lua strings are immutable, meaning they cannot be changed after creation.

They can be concatenated, sliced, and compared, but any modification will create a new string object.

Strings in Lua have a maximum length of 2^31 – 1 bytes and are encoded in UTF-8 by default. However, it is possible to use other encodings by manipulating the string bytes manually.

Below example demonstrates the initialization of strings in Lua:


local first_string = 'Single quotes'; local second_string = "double quotes"; local bracket_string = [[ This is a square bracket string. It is mostly used for multi-line strings. ]]print(first_string) print(second_string) print(bracket_string)

Escape Characters

Escape characters are special characters that allow us to include characters in a string that would otherwise be difficult or impossible to type directly.

These characters are represented using a backslash (\) followed by a special code.

The following table displays the available escape characters in Lua:

\nNew line
\rCarriage return
\vVertical tab
\”Double quotes
\’Single quotes
\[Left square bracket
\]Right square bracket

The following example implements the escape characters in Lua:


_str1 = "This is a string of _str1.\nAnother string of _str1." print(_str1)_str2 = "This is a string of _str2.\tAnother string of _str2." print(_str2)_str3 = "The is a string of \"_str3\"" print(_str3)_str4 = "This is a string of _str4 using a backslash \\" print(_str4)_str5 = 'This is a string of \'_str5\" print(_str5)

Lua String Methods

Lua supports the following string methods:


Returns the argument str with all its letters in uppercase.

Here is a brief example that uses string.upper in Lua:


local str = "MrExamples" local newStr = string.upper(str) print(newStr)


Returns the string passed as argument with all the alphabetical characters in lowercase.

Below example makes use of string.lower function in Lua:


local str = "MrExamples" local newStr = string.lower(str) print(newStr)

string.sub(str, i, j)

This method is used to extract a substring from a string. It takes two or three arguments: the string(str) from which to extract the substring, the starting index i (inclusive) of the substring, and the optional ending index j (inclusive) of the substring.

The following example demonstrates the string.sub method in Lua:


local str = "MrExamples" local newStr = string.sub(str, 3) print(newStr)


Replaces the occurrences of a pattern in a string with a new string or value.

Here, var is the string variable on which the operation is performed, find is the string to be replaced, replace is the string to be added in place of find while [n] is optional where the maximum number of replacements is to be specified.

If it is not specified, all occurrences are replaced.

Let’s explore the string.gsub() method using an example:


local str = "MrExamples: Learning through examples" local newStr = string.gsub(str, "through", "via") print(newStr)


This function finds the first occurrence of a pattern in a string and returns its starting and ending indexes.

Here, var is the string variable on which the operation is performed and find is the string that is being searched.

The argument named as first specifies the starting index of the search and is optional. Moreover, plain is a boolean value that specifies if the find value is a pattern or plain text. If this value is true, the find value is plain text. It is also optional.

For a clear understanding of string.find(), let’s take a look at an example:


text = "MrExamples!" substring = "Examples"start, finish = string.find(text, substring)print('start: '..start) print('finish: '..finish)

Lua string.reverse(str)

Used to reverse the order of characters in a string passed as an argument.

The following example demonstrates the string.reverse() method in Lua:


str = "MrExamples"reversed_str = string.reverse(str)print(reversed_str)

Lua string.format(str,…)

Returns a formatted string. Here str is the string that has placeholders for values while … represents values to be inserted into the placeholders.

Placeholders are specified below:

Place HoldersOverview
%d inserts an integer value.
%finserts a floating-point value.
%sinserts a string value.

To simplify the concept, let’s preview an example:


name = "Lua" year = 1993str = string.format("%s is a programming language that was built back in %d.", name, year)print(str)

Lua string.char(str)

This is a function in Lua that takes any number of integer arguments and returns a string consisting of the characters with the corresponding Unicode values.

Following example showcases the implementation of the string.char() method:


str = string.char(77, 114, 69, 120, 97, 109, 112, 108, 101, 115)print(str)

Lua string.byte(str)

It returns the ASCII value(s) of the character(s) at the specified position(s) in a string, given a string and an optional index.

In the absence of an index, the function returns the ASCII values of all characters.

Below example illustrates the string.byte() method in Lua:


str = "MrExamples"for i = 1, #str do value = string.byte(str, i) print(value) end

Lua string.len(str)

Returns the length of a string passed as an argument.

This is a brief example that covers the string.len() method in Lua:


str = "MrExamples"length_str = string.len(str)print(length_str)

Lua string.rep(str, n))

A string(str) and a count(n) are passed as arguments, and a new string is returned consisting of the original string repeated count times.

Following example provides an overview of string.rep() method in Lua:


str = "MrExamples " repeated_str = string.rep(str, 4)print(repeated_str)

Lua string.match(str, find)

Used to search a string(str) for a pattern(find) and returns the matching substring.

It takes two arguments:

First is the string to be searched, and the second is a pattern to match against.

Pattern matching is done using a combination of literal characters and special characters that have a specific meaning in Lua’s pattern matching syntax.

This example makes use of the string.match method in Lua:


str = "MrExamples: :Learning through examples" match = string.match(str, ":(%s+[^:]+)$")print(match)
We value your feedback.

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!

Leave a Reply

Your email address will not be published. Required fields are marked *