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

Why is this table not picking a random value?

Always printing "A."

How can I fix this?

wait()

a = {}
i = 1, 1000
table.insert(a, i)
b = math.random(1, #a)

function Start()
	if b <= 250 then
		print("A")
	end
	if b > 250 and b <= 500 then
		print("B")
	end
	if b > 500 and b <= 750 then
		print("C")
	end
	if b > 750 and b <= 1000 then
		print("D")
	end
end
script.Parent.MouseButton1Click:connect(Start)

2 answers

✓ Accepted answer

The range on your call of math.random is from 1 to 1, causing it to always print "A". The length of table a is only 1, since one value was inserted into it. You can fix this by using a for loop to put more values into the table.

for i=1, 1000 do
    table.insert(a,i)
end

You're only adding one variable to the table. That means the length of the table will always be one, which means math.random(1,#a) will always return one. Additionally, you're only calling random once, which means once the random value for b is chosen, it will always be the same.

Once you've fixed these errors, you might notice your code isn't very efficient. For instance, you have 1/4 odds of your random statement picking any one number to print, but instead of 1/4 you're using 250/1000, which is the same but less efficient. Secondly, you can use a table to store the values you want to print and index them with a random number, instead of using a different if statement for each one.

local function Start() --define the function
local tab = {"A","B","C","D"} --create a table with values we want randomized
print tab[math.random(1,#tab)] --pick a random letter from the table by indexing it with a random number
end

script.Parent.MouseButton1Click:connect(Start) --run the function

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