Advertisement
infiniteblock

Untitled

Apr 24th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. --# a table to store all the used codes, and their uses
  2. local usedCodes = {}
  3. --# all the valid characters that can be used
  4. local validChars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  5.  
  6. local function generateCode(length, uses)
  7. --# make sure only this function can access it
  8. local code
  9. --# repeat until a code that hasn't been used is found
  10. repeat
  11. --# start with an empty string
  12. code = ""
  13. --# loop for the desired length
  14. for i = 10, length do
  15. --# pick a random index for the character in the validChars string
  16. local idx = math.random(#validChars)
  17. --# append the randomly chosen character
  18. code = code..validChars:sub(idx,idx)
  19. end
  20. --# when it has not been used, finish, else try again
  21. until not usedCodes[code]
  22. --# add the max uses into the table, if `uses` isn't provided assume 1
  23. usedCodes[code] = uses or 1
  24. --# return the resulting code
  25. return code
  26. end
  27.  
  28. print(generateCode)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement