how can you make a random password generator in lua?

Viewed 69
 local function generator()

    local capital_letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
    local low_letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
    local numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}


    local Random_capital_letters = math.random(26)
    local Random_low_letters = math.random(26)
    local Random_numbers = math.random(10)
    local length = 10
    print("this is your generatet password: "..Random_capital_letters, Random_low_letters, Random_numbers[length])
    math.randomseed(os.time())
end


generator()

it just gives me an error all the time, would be cool if anyone could help me!

1 Answers
  1. You must initialize random seed before using math.random
  2. It's better to use length of your tables (capital_letters, low_letters, numbers) to use math.random function to pick a value and create your password.
  3. 10 value must not be in numbers table
  4. A loop is necessary to create your password : iterate from 1 to length and in each step, pick a random value in capital_letters, low_letters, numbers tables.

A working version adapted from your Lua code :

local function generator()

  local capital_letters = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
  local low_letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}
  local numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

  math.randomseed(os.time())

  local length = 10

  local pass = ""
  local choice = 0

  for _ = 1, length do
    choice = math.random(3)

    -- Capital letters
    if choice == 1 then
      pass = pass .. capital_letters[math.random(#capital_letters)]
    -- Low letters
    elseif choice == 2 then
      pass = pass .. low_letters[math.random(#low_letters)]
    -- Numbers
    else
      pass = pass .. numbers[math.random(#numbers)]
    end
  end

  print(pass)
end

generator()
Related