Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How do I make this If Statement print out the name of the value selected by math.random() ?

Asked by
D4_rrk 89
4 years ago

I am trying to print out the name of the value that has been selected by math.random(), I have a folder inside ReplicatedStorage which holds all the available power-ups, the error that I am receiving is:

Workspace.CoreScript:68: attempt to index number with 'Name' 

The script:

local powerUps = game.ReplicatedStorage.PowerUps:GetChildren()

local ranPowerUp = math.random(1, #powerUps)

                if ranPowerUp.Name == "Speed" then
                    print("Speed power-up has been selected!")
                end

2 answers

Log in to vote
3
Answered by 4 years ago
Edited 4 years ago

This is a common misconception with math.random(). It does NOT pass you back the object itself, it gives you as the name implies a random number. Instead we index the table using the random number, giving us that object.

local powerUps = game.ReplicatedStorage.PowerUps:GetChildren()

local ranPowerUp = math.random(1, #powerUps)

                if powerUps[ranPowerUp].Name == "Speed" then
                    print("Speed power-up has been selected!")
                end

EDIT: I also heavily recommend some randomness being added. Below will set a 'randomseed' based on the time, and proc a few randoms to better 'randomize' then number given. Its always a good idea.

math.randomseed(os.time())
math.random();math.random();math.random();
0
Thank you, it worked! D4_rrk 89 — 4y
0
math.random() will not change the internal seed; making calls will not adjust the "randomness". Ziffixture 6913 — 4y
0
Internally i know this, but it FEELS more random. Which makes it true. DinozCreates 1070 — 4y
Ad
Log in to vote
2
Answered by 4 years ago

ranPowerUp is a number, not a userdata value. You're assuming it's a userdata value, which it evidently isn't. You can index powerUps with ranPowerUp in a fashion such as powerUps[ranPowerUp], which should give you a userdata value from the table returned by GetChildren(). (Did you forget how GetChildren() works?)

Answer this question