lua-users home
lua-l archive

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


I would like to use a function to generate an string with "random"
characters. In my special case: the string must only use lower case
letters and digits. So the function should be able to accept character
ranges like defined in patterns. Its obvious to use the Lua pattern
system. Here is my first idea. Is it easy to implement such a function
based on the pattern system on the C side of Lua? If so - I will use
this "hack" until a friend supports me with that function in C.
Any suggestions are welcome.


   for Loop=0,255 do
      AllChars=AllChars..string.char(Loop)
   end


   function string.random(Length,Pattern)

-- Length (number)
-- Pattern (string, optional); e.g. %l%d for lower case letters and digits

      local Pattern,Random = Pattern or '.',''

      local String=string.gsub(AllChars,'[^'..Pattern..']','')

      for Loop=1,Length do
         Random=Random..
         string.char(string.byte(String,math.random(1,string.len(String))))
      end

      return Random

-- Random (string)

   end