My function "randomString" keeps the same result

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 in Lua to create passwords. However, whenever I call my ported function, it always returns the same output when 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 someone explain why? Thanks in advance!

+4
source share
1 answer

math.random generates a pseudo-random number sequence, which is a deterministic sequence that will resemble a real random sequence. The sequence generated by math.random will always be the same unless you use math.randomseed .

For each possible value with which you call math.randomseed , math.random will generate a different pseudo-random 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 must feed randomseed true random number before starting the generation.

+7
source

All Articles