Checking amount and values

I basically wanna check a folder for values, and make sure

  1. They have less than 10 values

and

  1. Make sure those values don’t add up to 10

Is this the most efficient way possible? It looks kinda bleh

-- Check if they are allowed to add fish to inventory
if #PlayerData.StoredFish:GetChildren() < 10 then
	-- Check individual values of each fish
	local TotalFish = 0
	for _, v in pairs(PlayerData.StoredFish:GetChildren()) do
		TotalFish = TotalFish + v.Value
	end
	
	if TotalFish < 10 then
		-- Update inventory
		local StoredFish = PlayerData.StoredFish:FindFirstChild(Data[player])
		if StoredFish then
			-- They have the fish already
			StoredFish.Value = StoredFish.Value + 1
		else
			-- Create the new value
			local StoredFish = Instance.new('IntValue')
			StoredFish.Name = Data[player]
			StoredFish.Value = 1
			
			StoredFish.Parent = PlayerData.StoredFish
		end
	end
end
1 Like

Your code is totally fine, it’s as good as it can be. Only thing I’ll suggest doing is, instead of looping through the stored fish to get how many fishes there are, you simply just do

local TotalFish = #PlayerData.StoredFish:GetChildren()
2 Likes

Reason that doesn’t work tho, is each value has a Value. So like for example, the folder might contain

Trout
    > 5
Salmon
    > 2

So if I did

local TotalFish = #PlayerData.StoredFish:GetChildren()

That would only return 2 (salmon and trout) but I need to also check to make sure their values don’t go past ten as well. So that’s why I loop through, so I get 7 as the total.

1 Like

You’re not showing us what the table Data[player] contains.

it’s just a string. Not really important to the question

How can we tell if it’s as efficient as possible if you don’t give all of the context?

Also it would be more readible if you stored the data in this manner.
PlayerData[player].StoredFish:FindFirstChild("Salmon")

Instead of:
PlayerData.StoredFish:FindFirstChild(Data[player])

That is very broad (Data[player]) and not very informative and could be misleading for someone, imo.

1 Like

PlayerData is stored as a folder under the Player instance.

Can a player ever have 0 of a type of fish? If a type of fish is always guaranteed to have more than 0 you can just count them and avoid having the if #PlayerData.StoredFish:GetChildren() < 10 check.