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

How do you pick a random value from a table?

Trying to get used to tables, and this won't work.

color = {"Bright red","Bright green","Bright blue"}
rand = math.random(1,#color)

for i=1,3 do
	script.Parent.BrickColor = BrickColor.new(color[rand])
	wait(1)
end

The brick starts out as black and changes to one of the colors and stops. No error in output, and I've tested multiple times. It should be changing colors 3 times, and it can't be changing to the same color 3 times in a row because I've tested it over 10 times and it always stays one color.

5 comments

1

You're on the right track, within those brackets "[]" you would want to put math.random(1,#color) 1 is the index value of the first object in color, and #color is the amount of objects in color. math.random will then in this case chose a number between 1 and 3.

0

I did what you said and it worked, so I'm guessing you can't use variables inside the "[]"?

0

You can use variables anywhere you want.

0

Why is it that when I use the variable "rand" inside the brackets it doesn't change colors 3 times but when I use math.random(1,#color) inside the brackets it works?

0

You are already setting rand to a number before you do the loop so in that loop rand is already set to that number, to make rand a different number each time you would declare rand = math.random(1,#color) inside your for loop :3

2 answers

✓ Accepted answer
color = {"Bright red","Bright green","Bright blue"}

for i=1,3 do
    rand = math.random(1,#color)
    script.Parent.BrickColor = BrickColor.new(color[rand])
    wait(1)
end

You would have to declare the rand variable in the loop as you declare it as a random number outside the loop meaning once that loop starts it's using that same random number it picked at the start and not changing it every time it loops.

1 comment

0

Thanks, this is the answer I was looking for.

-- You wont need the table with this script, but if you want it, I'm sure this script is off-topic
--color = {"Bright red","Bright green","Bright blue"}
rand = math.random (1,3)

scriptname = Script --Insert script name here for error message (not important)

if rand = 1 then
	script.Parent.BrickColor = BrickColor.new ("Bright red")
else
	if rand = 2 then
		script.Parent.BrickColor = BrickColor.new ("Bright green")
	else
		if rand = 3 then
			script.Parent.BrickColor = BrickColor.new ("Bright blue")
		else
			print ("Error: Random number was not found. This script is now prepared to be deleted!")
			print (scriptname.."is containing this error. Please go there as soon as possible")
		end
	end
end

2 comments

0

tf is this?

0

The script, but it doesnt use a table. Would you like me to explain?

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