string.reverse()

The string.reverse() function in Lua takes a string as input and returns a new string that contains the characters of the original string in reverse order. This can be useful for various applications, including text manipulation and encoding.

Syntax

string.reverse(s)

Parameters

  • Name
    s
    Type
    string
    Description

    The string that will be reversed.

Return Value

Returns a new string that is the reverse of the input string. If the input string is empty, an empty string is returned.

Examples

Example 1: Basic String Reversal

Reverse a simple string.

Example 1

local reversed = string.reverse("Hello")
print(reversed)  -- Output: olleH

Example 2: Reversing a Longer String

Reverse a longer string with spaces.

Example 2

local reversed = string.reverse("Lua Programming")
print(reversed)  -- Output: gnimmargorP auL

Example 3: Empty String

Demonstrate behavior when the input string is empty.

Example 3

local reversed = string.reverse("")
print(reversed)  -- Output: (empty string)

Example 4: Special Characters

Reverse a string containing special characters.

Example 4

local reversed = string.reverse("!@#")
print(reversed)  -- Output: #@!

Use Cases

  • Text Manipulation: Reversing strings for encoding or decoding data.
  • Data Processing: Useful in algorithms that require string reversal, such as palindromic checks.

See also

  • string.len(): Returns the length of a string, which can be helpful in combination with string.reverse() for processing.

Was this page helpful?

Table of Contents