Math.Random not working

Im trying to make a script where it prints an attack the NPC is going to fire and then fire’s it.

However everytime I launch the following script:

local Attack2 = "Eternal Vortex"
local Attack3 = "Galactic Beam"
local Attack4 = "Blackhole"
local Attack5 = "Daybreaker"
local Attack6 = "Solar Storm"
local Attack7 = "Explosive Astroid"
local TimeCooldown = math.random(5,12)

local CurrentAttack = {Attack1,Attack2,Attack3,Attack4,Attack5,Attack6,Attack7}
print(math.random(1, #CurrentAttack))

Instead of printing an attack from the list it prints a random number. image Instead of the name of an attack. I tried reversing this to

print(math.random(#CurrentAttack, 1))

Yet this doesn’t work either and instead it gives me an error.

In order to print the name of the attack within the table, you must do this:

print(CurrentAttack[math.random(1, #CurrentAttack)])

This way, you are referencing the index within the table to get your value. Also, I suggest moving all of the values into the CurrentAttack table so you don’t have to create a bunch of variables for each separate attack.

2 Likes

Oh thanks for the solution. I was confused why it didn’t work

1 Like

Also for future reference, you don’t need to set the array’s members like that. You can simply define it like so:

local CurrentAttack = {
     "Eternal Vortex";
     "Galactic Beam";
     "Blackhole";
     "Daybreaker";
     "Solar Storm";
     "Explosive Asteroid";
}

This is more efficient than initializing all of those variables.

1 Like