Code doesn't work for a reason

Hi,

So, I’ve made a script where whenever the player’s character gets added, the script will gets a random fruit and put it into the player’s backpack.

But whenever I run the code, it says "invalid argument #1 to ‘random’ (interval is empty)" Line 14

I’ve tried printing the data.Weight value and it give me the correct number, but when I try printing the sum value it just says the default value given.

Here’s the main code:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")

local fruitsData = require(ReplicatedStorage.FruitsData)

local fruits = ServerStorage.Fruits:GetChildren()

-- Gets a random fruit and returns an id to access the specific fruit
local function getRandomFruit()
	local sum = 0
	for id, data in ipairs(fruitsData) do
		sum += data.Weight
	end
	local rng = math.random(sum) -- Break point
	for id, data in ipairs(fruitsData) do
		if rng <= data.Weight then
			return id
		else
			rng -= data.Weight
		end
	end
end

Players.PlayerAdded:Connect(function(plr)
	print(plr.Name.." has joined the game!")
	plr.CharacterAdded:Connect(function()
		print(plr.Name.." spawned")
		
		local fruitId = getRandomFruit()
		if not fruitId then warn("Couldn't get fruitId") return end
		
		-- Access the fruit data with the id
		local newFruit = fruitsData[fruitId]
		
		for _, fruit in ipairs(fruits) do
			if fruit.Name:match(newFruit.Name) then
				local newfruit = fruit:Clone()
				newfruit.Parent = plr.Backpack
				print(newfruit.Name.." has been added to "..plr.Name.." with the weight of "..newFruit.Weight)
				continue
				else return
			end
		end
	end)
end)

FruitsData code:

return {
	[0.1] = {Name="GenoFruit",Weight=99};
	[0.2] = {Name="HarukoFruit",Weight=1}
}

Everything is appreciated!

You are missing arguments, math.random requires 2 Arguments.

1 for minimum
2 for maximum

Not really. I’ve tried replacing sum with 100 and it works fine

Your maximum number must be greater than your minimum number. This isn’t because you don’t have a 2nd argument, it’s because your maximum number is less than or equal to one.

1 Like

But the problem is when I print sum after the ipairs has finished, the sum value will still be 0

That might be because there’s nothing in the array because it’s a dictionary and it’s actually not an array, so you can’t use ipairs. Use pairs instead.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.