I've recently saw new 2 posts in Programs section with an solution for generating random strings. One of them used table of chars (O.o), second one was choosing a random character from a string-type matrix (Smart idea).
I don't say that any of those methods were incorrect, but there is one even simpler:
First of all, there is a thing called ASCII (If you don't know what it is - google it up). There is full table:
We are interested only in characters from 32 (Space) to 126 (~) - characters which can be understood by humans.
Second bit of a puzzle is math.random( a, b ) function, which generates an random number in range from a to b.
And third and last is string.char( i, […] ) which turns number(s) into character(s).
So you probably now have an idea how to do it :)/>, but if you don't that's how I did it:
function makeString(l)
if l < 1 then return nil end -- Check for l < 1
local s = "" -- Start string
for i = 1, l do
s = s .. string.char(math.random(32, 126)) -- Generate random number from 32 to 126, turn it into character and add to string
end
return s -- Return string
end
And if you don't want gave key generated, do something like that (thanks mudkip):
function makeString(l)
if l < 1 then return nil end -- Check for l < 1
local s = "" -- Start string
for i = 1, l do
n = math.random(32, 126) -- Generate random number from 32 to 126
if n == 96 then n = math.random(32, 95) end
s = s .. string.char(n) -- turn it into character and add to string
end
return s -- Return string
end