[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: ROT13 implementation in various languages
- From: Philippe Lhoste <PhiLho@...>
- Date: Fri, 22 Oct 2004 12:48:34 +0200
Just found a page, similar to the 99 Bottles of Beer on the Wall page,
which mentions Lua. The purpose is simple, a bit less trivial than Hello
World, though: to implement the ROT13 algorithm
<http://en.wikipedia.org/wiki/Rot13 >.
Oh, it is Roberto which implemented the algorithm! In Lua 4.
Before finding this page, I have made my own implementation (Lua 5),
given below in case somebody might be interested...
#!Lua-5.0.exe
-- ROT-13 text.
-- http://en.wikipedia.org/wiki/Rot13
-- by Philippe Lhoste <PhiLho(a)GMX.net> http://Phi.Lho.free.fr
-- v. 1.0 -- 2004/10/21 -- Creation
local text = "Put text to rotate here"
function Rotate13(t)
return (string.gsub(t, "[%a]",
function (char)
local bUpper = (char < 'a')
local b = string.byte(string.upper(char)) - 65 -- 0 to 25
b = math.mod(b + 13, 26)
if bUpper then
return string.char(b + 65)
else
return string.char(b + 97)
end
end
))
end
print(Rotate13(text))
One may make it more concise, but I often prefer readability over
terseness...
OK, I rewrite this to follow Roberto ideas. I have some hard time to
integrate (not forget) the "b and v1 or v2" paradigm, which is quite
similar to the C "b ? v1 : v2" which I missed when writing the code
above. Sigh.
function Rotate13(t)
local byte_a, byte_A = string.byte('a'), string.byte('A')
return (string.gsub(t, "[%a]",
function (char)
local offset = (char < 'a') and byte_A or byte_a
local b = string.byte(char) - offset -- 0 to 25
b = math.mod(b + 13, 26) + offset -- Rotate
return string.char(b)
end
))
end
Also more elegant because it doesn't rely on numeric Ascii values
(although Roberto let a '97' slip in the code...).
--
Philippe Lhoste
-- (near) Paris -- France
-- Professional programmer and amateur artist
-- http://Phi.Lho.free.fr
-- -- -- -- -- -- -- -- -- -- -- --