lua

How do i make a string in Lua contain random characters?


I'm curious on how to make a random string get printed out to the output in Lua I was wondering if this was possible for strings. because I know that you can generate random numbers using the function in Lua called. math.Random() but I'm not sure how to make a string random. how could I make characters in a string random that print to the output?

-- I want to print out random characters in a string to the consoles output
local Number = math.random(1,80) -- prints out a number 1-80
print(Number)

Solution

  • The capital letters are in string.char(math.random(65, 90)) and can be lazy lowered with another string method...

    local randuppercase = string.char(math.random(65, 65 + 25))
    local randlowercase = string.char(math.random(65, 65 + 25)):lower()
    
    print(randlowercase, randuppercase)
    -- Example output: g    W
    

    Without string method lower() lowercases start at...

    local randlowercase = string.char(math.random(97, 97 + 25))
    
    print(randlowercase, randlowercase:upper())
    -- Sample output: c    C
    

    Another possible solve is doing it more oldschool like...

    local chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" -- The Char Library
    local rint = math.random(1, #chars) -- 1 out of length of chars
    local rchar = chars:sub(rint, rint) -- Pick it
    
    print(rint, rchar)
    -- Sample Output: 12    L