Vital.sandbox
String

string.reverse

Shared

Returns a string with characters in reverse order


Syntax

local result = string.reverse(input)

Parameters

TypeNameDescription
stringinputString to be reversed

Returns

TypeNameDescription
stringresultString with all characters reversed

Examples

Reverse a word
local result = string.reverse("hello")

engine.print("info", result) --'olleh'
Reverse an entire sentence
local result = string.reverse("hello world")

engine.print("info", result) --'dlrow olleh'
Reverse a numeric string
local result = string.reverse("12345")

engine.print("info", result) --'54321'
Reversing a single character returns itself
local result = string.reverse("a")

engine.print("info", result) --'a'
Reversing an empty string returns empty
local result = string.reverse("")

engine.print("info", result) --''
Check if a string is a palindrome
local function isPalindrome(str)
    return str == string.reverse(str)
end

engine.print("info", isPalindrome("racecar")) --true
engine.print("info", isPalindrome("hello")) --false
Reverse a string and convert to uppercase
local result = string.upper(string.reverse("hello"))

engine.print("info", result) --'OLLEH'
Reverse a string with special characters
local result = string.reverse("hello!")

engine.print("info", result) --'!olleh'
Double-reversing returns the original string
local original = "test"
local reversed = string.reverse(string.reverse(original))

engine.print("info", reversed == original) --true
Reverse each word in a sentence individually
local sentence = "hello world"
local reversed = string.gsub(sentence, "%S+", function(word)
    return string.reverse(word)
end)

engine.print("info", reversed) --'olleh dlrow'
Create a mirror effect with a string
local text = "ABC"
local mirror = text.."|"..string.reverse(text)

engine.print("info", mirror) --'ABC|CBA'
Reverse a binary string
local binary = "1010"
local reversed = string.reverse(binary)

engine.print("info", reversed) --'0101'
Reverse a number represented as a string
local num = '123456'

engine.print("info", string.reverse(num)) --'654321'
Iterate over a string from end to start
local data = 'ABCDEF'

for i = 1, #data do
    local char = string.sub(string.reverse(data), i, i)
    engine.print("info", char)
end

--[[
Output: 
'F'
'E'
'D'
'C'
'B'
'A'
]]

On this page