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?
To get nice random numbers use: math. randomseed( os. time() )
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 to get a random number in lua. local randomNumber1 = math. random(1, 10) --Returns a number between 1 and 10.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With