string.byte() function in Lua programming


The string.byte() function is one of the most widely used Lua string library functions that takes a character or a string as an argument and then converts that character into its internal numeric representations.

The character to internal numeric representations can be easily interpreted from the ASCII table.

Syntax

string.byte(ch)
or
string.byte(ch,idx)

In the above representation of the string.byte() function, the ch identifier represents the character that we want to convert into a decimal value. Also, the idx identifier represents a character at that index of the string passed as an argument.

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

Example

Consider an example shown below −

 Live Demo

s = string.byte("a")
print(s)

Output

97

We can also pass a string in the argument to the string.byte() function, and if we don’t specify any index then that string will only print the first character’s internal integer representation.

Example

Consider the example shown below −

 Live Demo

s = string.byte("abc")
print(s)

Output

97

Example

Let’s consider an example where we will pass an index as the second argument to the string.byte() function. Consider the example shown below −

 Live Demo

s = string.byte("abc",2)
print(s)

Output

98

Note − The indexing of the string starts at 1.

Updated on: 19-Jul-2021

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements