0

Today I was writing a simple game in lua. A part of this game should choose a random element from a table and print it. Example:

test = { "foo", "bar", "test"}
print(math.random(#test))

The thing is: I'm always getting 1 when writing like that. If I miss something, then why does it work in the REPL?

Screenshot of the code and CMD It works in REPL Im using lua version 5.3.2.

BTW: Sorry for bad english.

nickkoro
  • 374
  • 3
  • 15
  • It doesn't work in the repl for me. – Eli Sadoff Dec 26 '16 at 22:38
  • Also, `#test` will just print the index, not the value itself. – Eli Sadoff Dec 26 '16 at 22:39
  • 2
    When using a random() function in almost every language if not in all languages, you have to use a seed value if you want to get different results per program execution. you should use something like math.randomseed(os.time()) before calling math.random(). – Stamatis Liatsos Dec 26 '16 at 22:48
  • ye, #test returns the length actually. So the number must be a number between 1 and #test. Right? – nickkoro Dec 26 '16 at 22:49

1 Answers1

3

You need to seed the random number generator.

Lua's math.random() function corresponds to C's rand() function.

In C, the rand() function returns the next value in a sequence determined by the initial seed. The default initial seed value is 1, which means that the program will use the same sequence each time it's run (which can be useful if you need reproducible results).

To get more nearly random results, you need to initialize the seed, for example, using the current time.

In C, this can be done like this:

srand(time(NULL));
int r = rand();

The corresponding Lua code is:

math.randomseed(os.time())
print(math.random())

Note that os.time() typically returns the current time as a whole number of seconds, so you'll get the same seed if you run your program twice within the same second. Also, C's rand() function and therefore Lua's math.rand() function, is generally not a high-quality pseudo-random number generator; do not use either for applications, like cryptography, requiring unpredictable values. (There are better PRNGs, but they're beyond the scope of this question.)

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 1
    Just one thing, on BSD and on Mac OSX there is an issue that if two seeds differ just by a small amount then the result from the random() will be identical. A workaround would be this math.randomseed( tonumber(tostring(os.time()):reverse():sub(1,6)) ) (source: http://lua-users.org/wiki/MathLibraryTutorial) – Stamatis Liatsos Dec 27 '16 at 01:54