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

Why is math.random() giving me problems?

So I have this script that is supposed to choose a random element of an array.

However, it isn't working.

Output gave me this: 17:06:56.907 - Workspace.Elections.Script:16: bad argument #2 to 'random' (interval is empty)

Here's the script:

while wait(0.1) do
	if script.Parent.SetUp.Value == true then
		SetUp.Value = false
		local MapChoices = {
			["Map1"] = "Map",
			["Map2"] = "Map",
			["Map3"] = "Map",
			["Map4"] = "Map",
			["Map5"] = "Map",
		}
		local ModeChoices = {
			["Mode1"] = "Mode",
			["Mode2"] = "Mode",
			["Mode3"] = "Mode",
		}
		local x = math.random(1, (#MapChoices))
		local y = math.random(1, (#ModeChoices))
		Choice1 = MapChoices[x]
		Choice1.Mode = ModeChoices[y]
		x = math.random(1, (#MapChoices))
		y = math.random(1, (#ModeChoices))
		Choice2 = MapChoices[x]
		Choice2.Mode = ModeChoices[y]
		x = math.random(1, (#MapChoices))
		y = math.random(1, (#ModeChoices))
		Choice3 = MapChoices[x]
		Mode = ModeChoices[y]
		wait(0.1)
	end
end

1 answer

✓ Accepted answer

When you're dealing with dictionaries, which is to say a "table" you can index with things other than numbers. Lua loses the ability to tell you how many elements are in said table.

For your purposes it doesn't seem like you actually need your tables indexed by strings so simply either remove the manual indexing or set it to a number. For example:

local mapChoices = {
	[1] = "Map1";
	[2] = "Map2";
	[3] = "Map3";
	[4] = "Map4";
	[5] = "Map5";
};

-- which is the same as:

local mapChoices = {
	"Map1";
	"Map2";
	"Map3";
	"Map4";
	"Map5";
};

local index = math.random(#mapChoices);
print(mapChoices[index]);

3 comments

0

bad argument #1 to 'random' (interval is empty)

0

He just gave you the solution.

0

Sorry about that. Forgot to change something with the rest of the code.

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