# How to make a script choose a random number between 1 and 100?

Hi, i’m pretty new to Lua coding so please excuse me if this is extremely easy or something. I already looked at the wiki but it was all to confusing to me. I’m trying to make a swep do a random amount of damage between 1 and 100 but I cant find any straight google answers to help. I can only find really complicated ones that I cant understand haha. All I ask is for a little help and maybe an explanation on what parts of it makes the script choose the random number? Thank you!

http://wiki.garrysmod.com/page/math/random is what you’re after.

Try something like this:

[lua]
local randomthing = math.random(1,100)
[/lua]

edit:
slightly ninja’d

Thank you both for the help. I have no idea what i’m doing, but assuming that i’m making a swep that will in turn give the targeted player health, this will work?

``````
SWEP.HealAmount = ( math.Rand( 30,100 ) )

``````

Show all the code in your SWEP,

and math.Rand returns a float, use math.random(startNum, endNum) to return an integer

Sorry for the wait, heres a pastebin of it. I’m making it a TTT weapon :).

And I tested it using the math.Rand and it seemed to heal 90 HP every time even though it was 30,100

That’s because self.HealAmount is being initialized once, so all you have to do is declare self.HealAmount again in the primaryattack function when it’s needed

Sorry, I have no idea >.<
I’ve changed math.Rand to math.random as well

When you declare SWEP.HealAmount in your SWEP outside a function in the main scope that will initialize it. It runs math.random once, so it will only give you a random number one time.

[lua]
if ( IsValid( ent ) && ( ent:IsPlayer() or ent:IsNPC() ) ) then
self.HealAmount = math.random(30,100)
[/lua]

Okay, so do I do something like

``````
if ply:Health is >== 100 then return end

``````

? I’m completely new to doing this kind of stuff, I apologize

You also might want to look at some basic lua tutorials because from that post you just made, it doesn’t look like you even know how to use arithmetic operators.

Oh crap I didn’t see the code in your last post, my bad. I’ve followed goature’s (If you know who he is) and a few other gmod wiki tutorials but none of it sticks in me. I really want to learn and have been trying for some time but it’s like teaching high school to a fifth grader with me. Thank you for your help though, I appreciate it

[editline]23rd February 2014[/editline]

This is what i’ve done now, is this okay?

http://puu.sh/784tf.png

That code is directly from your PrimaryAttack function, all I did was add the line in. If you don’t understand something, keep on reading it over and over again to yourself.

You gotta close your if statement.

[editline]23rd February 2014[/editline]

And it has to be inside one of the weapon’s hooks.