lua-users home
lua-l archive

Re: string.random

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Markus Huber wrote
I would like to use a function to generate an string with "random"
characters. ...
This should be faster than the hack you supplied, as it
1/ only creates patterns once, and
2/ uses table.concat for the string concatenations.
3/ uses table lookups rather than string.char.
(but i haven't tested it - this is just an outline)
Adrian
<CODE>
do -- block for upvalues
 local AllChars = {}
 for Loop=0,255 do
 AllChars[Loop+1]=string.char(Loop)
 end
 local AllString = table.concat(AllChars)
 local Built = {'.',AllChars}
 local function AddLookup(Pattern)
 local S=string.gsub(AllString,'[^'..Pattern..']','')
 local Lookup = {}
 for Loop=1,string.len(S) do
 Lookup[Loop] = string.sub(S,Loop,Loop+1)
 end
 Built[Pattern] = Lookup
 return Lookup
 end
 function RandomString(Length,Pattern)
 -- Length (number)
 -- Pattern (string, optional);
 -- e.g. %l%d for lower case letters and digits
 local Pattern = Pattern or '.'
 local Lookup = Built[Pattern] or AddLookup(Pattern)
 local Range = table.getn(Lookup)
 local Result = {}
 for Loop=1,Length do
 Result[Loop] = Lookup[math.random(1,Range)]
 end
 return table.concat(Result)
 end -- function
end -- do
</CODE>
Adrian

AltStyle によって変換されたページ (->オリジナル) /