How to make a item bought limit

So I’ve ran into this error where basically you can purchase more than one model of the same item, therefore instead of buying one flashlight, you could buy 30. This obviously can be solved with a limit being set on the item, but I’m not quite sure how to create this limit. Current script for buying a item in shop:

game.ReplicatedStorage.ToolEvents.FlashlightEvent.OnServerEvent:Connect(function(player)
	if player.leaderstats.SoulTokens.Value >=10 then
		player.leaderstats.SoulTokens.Value = player.leaderstats.SoulTokens.Value -10
		game.ServerStorage.Tools.Flashlight:Clone().Parent = player.Backpack
	end
end)

By the way this script is located in ServerScriptService

2 Likes

You can iterate over the player’s backpack and count the number of a specific tool they own.

2 Likes

Yeah but I don’t know what to put for the script (I’m still learning LUA)

1 Like

You can use a for loop:

local amount = 0
for _, tool in ipairs(plr.Backpack:GetChildren()) do
    if tool.Name == "Flashlight" then
        amount += 1
    end
end
3 Likes

Like this?

local amount = 0

game.ReplicatedStorage.ToolEvents.FlashlightEvent.OnServerEvent:Connect(function(player)
	if player.leaderstats.SoulTokens.Value >=10 then
		player.leaderstats.SoulTokens.Value = player.leaderstats.SoulTokens.Value -10
		game.ServerStorage.Tools.Flashlight:Clone().Parent = player.Backpack
		for _, tool in ipairs(plr.Backpack:GetChildren()) do
			if tool.Name == "Flashlight" then
				amount += 1
			end
		end
	end
end)
game.ReplicatedStorage.ToolEvents.FlashlightEvent.OnServerEvent:Connect(function(player)
	if player.leaderstats.SoulTokens.Value >=10 then
		local amount = 0
		for _, tool in ipairs(plr.Backpack:GetChildren()) do
			if tool.Name == "Flashlight" then
				amount += 1
			end
		end
        if amount <= 30 then
            game.ServerStorage.Tools.Flashlight:Clone().Parent = player.Backpack
            player.leaderstats.SoulTokens.Value = player.leaderstats.SoulTokens.Value -10
        end
	end
end)
1 Like