Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My 'randomString' function keeps returning the same result

Tags:

random

lua

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!

like image 385
Bicentric Avatar asked Mar 23 '23 08:03

Bicentric


1 Answers

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.

like image 63
Lorenzo Donati -- Codidact.com Avatar answered Mar 29 '23 23:03

Lorenzo Donati -- Codidact.com