This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
kaioo1312's profile picture

Random Code Generator

Started by kaioo1312, 10 September 2014 - 03:01 PM
kaioo1312 #1
Posted 10 September 2014 - 05:01 PM
Ok, so i've been wanting this for a program that I have been making for a while now but I can never get it to work. I know things like this exist:

local t = {1, 2, 3, 4, 5}
a = math.random(1, #t)
print(a)
However, this generator needs to be capable of generating a code with number, lower-case letters and upper-case letters, which for my skill is proving difficult.

Any help would be appreciated

Thanks

~kaioo1312
MKlegoman357 #2
Posted 10 September 2014 - 07:05 PM
You could probably think of million ways of how to do it, but what looks simplest to me is making a string with each lower/upper case letters, numbers, special symbols or anything else you might like and building the random key from that:


local chars = "abcdABCD123#$@"
local randomLength = 8

local key = ""

for i = 1, randomLength do
  local rnd = math.random(#chars)
  key = key .. chars:sub(rnd, rnd)
end

print(key) -->> example: CaD$b1cA

EDIT: derpy me, fixing my errors that TheOddByte found.
Edited on 10 September 2014 - 05:18 PM
TheOddByte #3
Posted 10 September 2014 - 07:13 PM
-Snip-
Wouldn't that be

local chars = "abcdABCD123#$@"
local length = 8

local key = ""
for i = 1, length do
	local index = math.random( 1, #chars )
	key = key .. chars:sub( index, index ) )
end

print( key )
Since you're using it as chars were a table( trying to access an index )

Edit: Fixed my code aswell, didn't realize I messed up before .-.
Edited on 10 September 2014 - 06:10 PM
MKlegoman357 #4
Posted 10 September 2014 - 07:20 PM
-snip-

Oh, how did I missed that? Anyway, fixed my code now (your suggested solution still has some issues which you can find in my above post ;)/> ).
kaioo1312 #5
Posted 11 September 2014 - 04:47 PM
Thanks guys