Indigo Rose Software
  #1  
Old 12-04-2007
Dermot Dermot is offline
Indigo Rose Customer
 
Join Date: Apr 2004
Location: Vancouver, Canada
Posts: 1,520
Generate Random Strings

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

Code:
--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
Code:
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...f-string.upper
__________________
Dermot

AMS Add-ons - xDialog.com

A complex system that does not work is invariably found to have evolved from a simpler system that worked just fine.
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
random numbers lnd AutoPlay Media Studio 6.0 3 05-17-2007 03:15 AM
Random text from tables. MIchaelD AutoPlay Media Studio 5.0 0 09-20-2004 10:36 AM
Comparing Two Strings Desmond AutoPlay Media Studio 5.0 Examples 0 10-03-2003 02:23 PM
Generate Random Value (Action Properties) SpaceStationAlpha Setup Factory 6.0 1 04-15-2002 02:10 PM


All times are GMT -6. The time now is 11:46 PM.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Copyright © 2000 - 2009 Indigo Rose Corporation. All rights reserved.
Indigo Rose Software