string.sub() function in Lua


Another important function of the Lua’s string library is the string.sub() function. The string.sub() function is used to extract a piece of the string.

The string.sub() function takes three arguments in general, the first argument being the name of the string from which we want to extract a piece, the second argument is the i-th index or say, the starting index of the string piece that we want, and the third and the last argument is the j-th index of the last index of the string piece we want.

It should be noted that both the starting index and the ending index, i.e., the second and the third argument are inclusive.

Syntax

string.sub(s,i,j)

In the above syntax, the s identifier is used to denote the string from which we are extracting a substring, the i is the starting index of the substring and the j identifier is the ending index of the substring.

An important point to note about the string indices is that the indexing start from 1 not 0, so the first character of the string is at index 1.

Example

Let’s consider a few examples where we will make use of the string.sub() function.

Consider an example shown below −

 Live Demo

s = "hello world"
x = string.sub(s,1,5)
print(x)

Output

hello

Example

Another example on the same string −

y = string.sub(s,7,10)
print(y)

Output

worl

We can also pass negative indexes inside the arguments (second and third argument) of the string.sub() function; the negative indices are used to count from the end of the string.

Example

Consider the following example −

 Live Demo

s = "[in code]"
print(string.sub(s, 2, -2))

Output

in code

Updated on: 08-Sep-2023

39K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements