Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

why does my math.random script always return 10?

local damage = tool:WaitForChild'Damage'.Value
local maxDamage = tool:WaitForChild'MaxDamage'.Value
damageCal = math.random(damage,maxDamage)
print(damageCal)
print(damageCal)

just in case you were wondering the values damage is 5 and the value for max damage is 10

2 comments

1

Well, because of math.randomseed(). try putting a wait(1) infront of the math.random, and then you'll get something different. Or try it in the command bar

1

And it only makes damageCal once, it will print the same thing in those two prints

1 answer

✓ Accepted answer

Small notice: I'm not on my laptop right now, and I'm currently using a computer at the library with a Godawful keyboard. So if I made some illegible typos, I appologize ahead of time.

Patterns

This is because the order in which math.random selects its numbers is entirely based off a seed. The "seed" in this case, is a number in which sets the path for a sequence of numbers that is deemed "random".

Why do you need to know this?

Well, there's actually a function you may or may not be aware of that can handle situations such as this in the math library, called math.randomseed. This function takes one argument, which is a number, and sets it as the RNG seed that defines what sequence the numbers turn up in.


How do I use math.randomseed?

Well as I said before, the random numbers are based off the seed. Same seed, same set of numbers. Which means if you want a truly random set of numbers each time, you're going to need a different seed each time. But what number can you use that's constantly changing...? Time!


You can simply use time that tick or os.time returns as the seed for the math.randomseed function, and that should suffice. Here's an example:

-- This is probably most conveniently written at the beginning of your script
math.randomseed(os.time())

-- Print a random number between 1 and 10
print(math.random(10))

This would be opposed to using a constant seed, where if I said something like this, we'd get the same set of numbers constantly:

math.randomseed(1) -- Constant seed

-- Print a random number 1 through 10, five times
for i = 1,5 do
	print(math.random(10))
end

The code above should yield this result every time, the first time it's ran:

6 2 2 8 9

Anyway, hope that helped. Just let me know if you have any questions.

4 comments

0

Nice random bolding

0

everytime i run this, i keep getting 8

0

vever mind, i didnt scroll donw engough, i didnt notice there was more text at the bottom

0

ok i dont know why math.random was workin perfectly fine before now it suddently doesnt even work

This discussion is preserved as it was. New answers, comments, and votes are closed.