Dermot
12-04-2007, 02:13 AM
Here is a nice function I found for generating random strings. I have used the one posted here http://www.indigorose.com/forums/showthread.php?t=9277 but found that using it more than once inside a loop would generate duplicate strings.
I take no credit for the function below. I found it here http://lua-users.org/wiki/RandomStrings
--Generate random strings with defined char-sets using the Lua internal character classes. Idea from Adrian Sietsma.
local Chars = {}
for Loop = 0, 255 do
Chars[Loop+1] = string.char(Loop)
end
local String = table.concat(Chars)
local Built = {['.'] = Chars}
local AddLookup = function(CharSet)
local Substitute = string.gsub(String, '[^'..CharSet..']', '')
local Lookup = {}
for Loop = 1, string.len(Substitute) do
Lookup[Loop] = string.sub(Substitute, Loop, Loop)
end
Built[CharSet] = Lookup
return Lookup
end
function string.random(Length, CharSet)
-- Length (number)
-- CharSet (string, optional); e.g. %l%d for lower case letters and digits
local CharSet = CharSet or '.'
if CharSet == '' then
return ''
else
local Result = {}
local Lookup = Built[CharSet] or AddLookup(CharSet)
local Range = table.getn(Lookup)
for Loop = 1,Length do
Result[Loop] = Lookup[math.random(1, Range)]
end
return table.concat(Result)
end
end
Use like this
result = string.random(16, "%l%d%u")
Will return a 16 charactor string like this 'Ux6THy5dsqMx7l8j'
Passing a CharSet (Pattern) is optional but using it you can control the string that is generated. Here is a very good explanationof lua patterns http://www.lua.org/manual/5.1/manual.html#pdf-string.upper
I take no credit for the function below. I found it here http://lua-users.org/wiki/RandomStrings
--Generate random strings with defined char-sets using the Lua internal character classes. Idea from Adrian Sietsma.
local Chars = {}
for Loop = 0, 255 do
Chars[Loop+1] = string.char(Loop)
end
local String = table.concat(Chars)
local Built = {['.'] = Chars}
local AddLookup = function(CharSet)
local Substitute = string.gsub(String, '[^'..CharSet..']', '')
local Lookup = {}
for Loop = 1, string.len(Substitute) do
Lookup[Loop] = string.sub(Substitute, Loop, Loop)
end
Built[CharSet] = Lookup
return Lookup
end
function string.random(Length, CharSet)
-- Length (number)
-- CharSet (string, optional); e.g. %l%d for lower case letters and digits
local CharSet = CharSet or '.'
if CharSet == '' then
return ''
else
local Result = {}
local Lookup = Built[CharSet] or AddLookup(CharSet)
local Range = table.getn(Lookup)
for Loop = 1,Length do
Result[Loop] = Lookup[math.random(1, Range)]
end
return table.concat(Result)
end
end
Use like this
result = string.random(16, "%l%d%u")
Will return a 16 charactor string like this 'Ux6THy5dsqMx7l8j'
Passing a CharSet (Pattern) is optional but using it you can control the string that is generated. Here is a very good explanationof lua patterns http://www.lua.org/manual/5.1/manual.html#pdf-string.upper