What is the Lua string.byte() function?

In the Lua programming language, the string.byte() function is widely used because it provides a convenient way to work with individual bytes in a string. It is a string library function that accepts a character or a string as input and outputs an internal numeric representation comparable to ASCII.

Syntax

The syntax of the string.byte() function is as follows:

string.byte(str, index)

Parameters

The string.byte() function takes two arguments, where:

  • The str is the string or a character.

  • The index represents an index of a letter or a character in the provided string. This parameter is optional. If we do not pass this argument, the default value of index will be 1.

The string.byte() function returns the ASCII of the provided character, or if the given input is a string, then returns the ASCII of the first character or the value at a specified index.

Example

Let’s demonstrate the use of the string.byte() function:

local str = "Hello, World!"
local character_ASII = string.byte(str)
local string_ASCII = string.byte(str, 4)
print(character_ASII)
print(string_ASCII)

Explanation

  • Line 1: It defines a local variable named str and assigns it the “Hello, World!” string.

  • Line 2: It defines another local variable named character_ASII. It uses the string.byte function to obtain the ASCII value of the first character in the str string, which is “H.” The character_ASII variable then holds the ASCII value of “H,” which is 72.

  • Line 3: It defines yet another local variable named string_ASCII. It also uses the string.byte function, but this time with two arguments. The first argument is the str string, and the second argument (4) specifies the position within the string to obtain the ASCII value. In this case, it extracts the ASCII value of the character at the 4th position in the str string, which is “l.”

  • Lines 5–6: It prints the value of the character_ASII and string_ASCII variables.

The string.byte() function may be used to examine individual characters in a string during processing, which facilitates data manipulation and parsing. We can compare characters numerically by comparing their byte values. This is useful for sorting or searching operations to compare characters regardless of their visual representation.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved