I am trying to reverse a string in Lua without using the string.reverse() function. Here is my code –
function reverseStr(s)
return string.gsub(s, "(.)(.)", "%2%1")
end
The code is currently only reversing the first two characters in the string, and I am wondering what I can do to make the function reverse every character in the string.
abc — cba
bbc — cbb
dka — akd
Thank you!
You can’t make Lua’s pattern matching system reverse a string. You have to either write the obvious reversing code (iterating through the string backwards, building a new table from strings in reverse order, and using
table.concat) or usestring.reverse.