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

Hello There!
I am Trying to Make A Script which Randomly Picks a Food Model In A Folder Called “ClickableFood” and Randomize Its Position.

When I Test the Script, I Get The Error : invalid argument #1 to 'random' (interval is empty)
The Error Hangs Up on the Line image

Here is the Full Script :

local FoodPositionEvents = game.ReplicatedStorage.FoodPositionEvents

FoodPositionEvents.Position1.OnServerEvent:Connect(function()

	local FoodsFolder = game.Workspace.ClickableFood
	local FoodPositionsFolder = game.Workspace.FoodPositions

	local Foods = FoodsFolder:GetChildren()
	local RandomFoodIndex = math.random(#Foods)
	local ChosenRandomFood = Foods[RandomFoodIndex]
	print(ChosenRandomFood)

	local Positions = FoodPositionsFolder:GetChildren()
	local RandomPositionIndex = math.random(#Positions)
	local ChosenPosition = Positions[RandomPositionIndex]
	print(ChosenPosition)
	script.Position1.Value = ChosenPosition.Name
	wait(0.5)
	
	local SelectedFoodClone = FoodsFolder:FindFirstChild(ChosenRandomFood.Name):Clone()
	local ThePositionPart = FoodPositionsFolder:FindFirstChild(ChosenPosition.Name)

	SelectedFoodClone.Parent = game.Workspace
	for i, v in pairs(SelectedFoodClone:GetChildren()) do
		if v:IsA("Part") then
			v.Position = ThePositionPart.Position
			wait(0.2)
			v:FindFirstChild("ClickBox").Position = v.Position
		end
	end
end)

Thanks for Reading!

2 Likes

Check if length of the table it’s zero.
Before Lua 5.3 (therefore Luau which is based on 5.1), math.random(x) is essentially math.random(1, x), and 1 > 0 therefore it errors because the minimum is higher than the maximum.

6 Likes

You forgot to put a number before your first argument on your math.random function call

EDIT: sorry my brain broke not sure if this is accurate, so do as @Blockzez suggested

If you use math.random(#table) then it picks from 1 - the length of the table.

Yep sorry about that, I made a mistake

I Did Not Quite Understand What You Mean to Say. If i Am Right, i checked the Folder which Contains the Food Models

The length of the FoodFolder is zero, based on the error message (no other positive integers unless overflown will throw an error for math.random(#x) with a message like this).

If you print #Foods, you might find that it prints 0, and math.random(0) errors in Luau.

1 Like