util.string.reverse

Shared

Returns a string with characters in reverse order


Syntax

local result = util.string.reverse(
    input
)

Parameters

TypeNameDescription
stringinputString to reverse

Returns

TypeNameDescription
stringresultString with all characters reversed

Examples

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

On this page