Making a random letter picker better

I’ll keep this short, as always.

Let’s say you want to get a random letter from the alphabet, so you go ahead and do this:

local alphabet = {"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 letter = alphabet[math.random(1,#alphabet)]

As you can see, there’s an extremely long table of letters.

This is what I want to try to do, to make life easier:

local alphabet = "abcdefghijklmnopqrstuvwxyz"

local letter = --???

Is there a way to get all of the letters from that one string? Please let me know.

You can generate a random number between 1 and the amount of letters in the alphabet and then get the letter in the alphabet by using string.sub()

local alphabet = "abcdefghijklmnopqrstuvwxyz"

local randomValue = math.random(1, #alphabet)
local letter = string.sub(alphabet, randomValue, randomValue)
1 Like

So just something like this:

local alphabet = "abcdefghijklmnopqrstuvwxyz"

local letter = math.random(1,string.len(alphabet))


Adding onto the previous method, another way to get a random letter would be the use of string.char to convert a number code to a character.

local minCharCode = 97 -- numeric code for the character "a"
local maxCharCode = 122 -- numeric code for the character "z"
-- capital letters range from numbers 65 to 90.

local randomLetter = string.char(math.random(minCharCode, maxCharCode))

@denkodin’s method was more simple, using string.sub(). Thanks for your help too, though.

This is generally the best option, unless you’re looking to type out the alphabet every time you want a letter.

1 Like

Typing one string is easy enough, I didn’t want an absurdly long table.

What does this even mean. First, 26 entries is not absurdly long. Second, it literally probably takes an extra 100 bytes of data to have that table. Third, that’s not even what my post was referring to.

I was saying that the string.char solution is the best, because it is future proof.