Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua math.random not working

Tags:

random

lua

So I'm trying to create a little something and I have looked all over the place looking for ways of generating a random number. However no matter where I test my code, it results in a non-random number. Here is an example I wrote up.

local lowdrops =  {"Wooden Sword","Wooden Bow","Ion Thruster Machine Gun Blaster"}
local meddrops =  {}
local highdrops = {}

function randomLoot(lootCategory)
    if lootCategory == low then
        print(lowdrops[math.random(3)])
    end
    if lootCategory == medium then

    end
    if lootCategory == high then

    end
end

randomLoot(low)

Wherever I test my code I get the same result. For example when I test the code here http://www.lua.org/cgi-bin/demo it always ends up with the "Ion Thruster Machine Gun Blaster" and doesen't randomize. For that matter testing simply

random = math.random (10)
print(random)

gives me 9, is there something i'm missing?

like image 751
user2677006 Avatar asked Aug 13 '13 02:08

user2677006


People also ask

How do you do math random in Lua?

To get nice random numbers use: math. randomseed( os. time() )

How does Lua RNG work?

Lua random is one of the mathematical concept and it's a library function that can be used for to generate the pseudo-random numbers and it can be called in different ways like the method called without arguments and it will be return with pseudo-random real type of numbers with some uniform distributions time ...

How do you generate random integers in Lua?

how to get a random number in lua. local randomNumber1 = math. random(1, 10) --Returns a number between 1 and 10.

What does math Floor Do in Lua?

The floor value of a number is the value that is rounded to the closest integer less than or equal to that integer. Lua provides us with a math. floor() function that we can use to find the floor value of a number.


1 Answers

You need to run math.randomseed() once before using math.random(), like this:

math.randomseed(os.time())

One possible problem is that the first number may not be so "randomized" in some platforms. So a better solution is to pop some random number before using them for real:

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

Reference: Lua Math Library

like image 115
Yu Hao Avatar answered Oct 09 '22 12:10

Yu Hao