Logo

Programming-Idioms

History of Idiom 41 > diff from v35 to v36

Edit summary for version 36 by programming-idioms.org:
[Lua] Var name t

Version 35

2018-01-03, 23:24:55

Version 36

2018-01-03, 23:26:00

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.

Illustration

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.

Illustration
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)
Code
function utf8.reverse(s)
	local r = ""
	for p,c in utf8.codes(s) do
		r = utf8.char(c)..r
	end
	return r
end

t = 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
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
Doc URL
http://www.lua.org/manual/5.3/manual.html#6.5