2

my problem is when i write math.random(10) it is not actually random it always give me output:

1 6 2 9

and if i have used for example:

local colors = {"ORANG","BLUE","RED","YELLOW","BLACK"}
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
print(colors[math.random(#colors)])
os.execute 'pause'

The output is always:

ORANGE
RED
ORANGE
BLACK
RED
RED
BLUE BLACK

This is always the output, how could it be random????

mogogogo
  • 107
  • 7

2 Answers2

6

You're misunderstanding what random does:

It's a pseudorandom number generator. This means that, given a specific seed, it will always give you the exact same sequence of numbers.

Typically, you use a seed from an external source, e.g. use the current time as seed (WARNING: This is cryptologically dangerous!).

Please read up on pseudorandom and how to use Lua's random library.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
4

I found the answer, you need to put:

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

before using math.random()

mogogogo
  • 107
  • 7
  • 3
    But make sure to call `math.randomseed` only *once* in your program, not every time you call `math.random`. – lhf Jun 04 '15 at 11:22