Logo

Programming-Idioms

History of Idiom 41 > diff from v25 to v26

Edit summary for version 26 by :
New Lua implementation by user [Nepta]

Version 25

2016-02-18, 16:57:59

Version 26

2016-04-07, 09:20:58

Idiom #41 Reverse a string

Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

Idiom #41 Reverse a string

Create string t containing the same characters as string s, in reverse order.
Original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.

Code
function utf8.reverse(s)
	local r = ""
	for p,c in utf8.codes(s) do
		r = utf8.char(c)..r
	end
	return r
end

r = utf8.reverse(s)
Comments bubble
if string s is an ascii string you can directly use string.reverse instead.

You will also need Lua5.3 or an utf8 module
Doc URL
http://www.lua.org/manual/5.3/manual.html#6.5