randomString.lua
----------------------------------------------------------------------------
-- File: randomString.lua
-- Author: Don Draper
--
-- This is the Lua implementation of my simple 'randomString' function
-- which I previous wrote in PAWN.
----------------------------------------------------------------------------
randomString = {}
local randomCharset = {
"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",
"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",
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
}
function randomString.generate(length)
local currentString = ""
for index = 1, length do
currentString = currentString .. randomCharset[math.random(1, #randomCharset)]
end
return currentString
end
Test.lua
require("randomString")
print(randomString.generate(16))
io.read()
So here is my 'randomString' function which I originally wrote in the PAWN programming language, I thought I would implement it to Lua to generate some password salts. However whenever I call my ported function it always returns the same output whenever I first run the program.
Take this piece of code for example.
for i = 0, 100 do
print(randomString.generate(16))
end
It will always generate the same list of random strings. Can anyone please explain why? Thanks in advance!
math.random generates a sequence of pseudorandom numbers, that is a deterministic sequence that will resemble an actual random sequence. The sequence generated by math.random will be always the same, unless you use math.randomseed.
For every possible value with which you call math.randomseed, math.random will generate a different pseudorandom sequence.
Try this, for example, and you will see a different sequence:
math.randomseed( 7654321 )
for i = 0, 100 do
print(randomString.generate(16))
end
If you want a truly random sequence you should feed randomseed with a true random number before starting the generation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With