math.random question

I would like to use math.random to print a random number in the console. So… How does the code need to look? Here’s what I was thinking:


local number = math.random( 1, 10 )
if number == 1 then print( "You got the number one!" )

I am so lost on formatting and proper terms, could someone please help a bit?

Thanks for looking and I hope for your reply,
Double 117.

So far so good… I’m going to assume this snippet is inside of a properly formatted function. Make sure you put an “end” after the “if-then” statement.

Also, if you intend to print that message to the console, print or Msg will suffice. However, if you want to send it to a player, then you would use something like:
[lua]LocalPlayer():PrintMessage(HUD_PRINTTALK, “You got the number one!”)[/lua]

If I were you I’d save myself a lot of trouble and concatenate the number with a string.
Example :
[lua]number =10
string = “Your number is “…number…”!”
print(string) //Prints “Your number is 10!”[/lua]

Or why not:
[lua]print(“You got the number “…math.random(1,10)…”!”)[/lua]

I think an if always needs an end, even if you intend to have it on one line.

But considering the atrocities some people post when they’re new to Lua, your code snippet is very well written.

Well thanks MegaJohnny, I have been reading as much as possible about Lua coding in GMOD so I am happy to see it is paying off. So shs, when you say “I’m going to assume this snippet is inside of a properly formatted function,” do you mean something like this: (I am still clueless when it comes to formatting)


function playerRespawn( ply )

local number = math.random( 1, 10 )

     if number == 1 then
LocalPlayer():PrintMessage(HUD_PRINTTALK, "You got the number one!")  
     
     end
end

hook.Add( "PlayerSpawn", "playerRespawnTest", playerRespawn )

Anyways, thanks everyone for helping me. I posted in this sub-forum before and got a bunch of dumb ratings. So thanks.

[lua]function PickANumber()
local number = math.random( 1, 10 )
if number == 1 then
LocalPlayer():PrintMessage(HUD_PRINTTALK, “You got the number one!”)
end
end[/lua]

There is no “proper” way of formatting your code, as long as the syntax is correct then you are good. However there are a few “preferred” ways of formatting your code, especially when it comes to tabbing. You should generally have a new tab when entering a new block (In a function, if statement, loop etc).

Oh, ok, I see. Thanks.