How effective is this gsub to keep duplicate values?

There is sometimes duplicates that the player might have, but I need to subtract certain values from the string when the player does something. I only need to subtract one thing from their value, and not more than one if they have “Pizza” twice.

    local TakeAway, remainder = string.gsub(player.Folder.Food.Value, "Pizza", "")
	player.Folder.Food.Value = TakeAway
	if remainder > 1 then
		for i = 1,remainder-1 do
			player.Folder.Food.Value = player.Folder.Food.Value.."Pizza"
		end
	end

This is what I came up with. It does work, but, it sometimes bugs if they have only one pizza, it just creates a space and puts pizza again, even though it should remove it entirely. If there is a more effective way of doing something like this, I am all ears. It does create a lot of whitespace, but I have a separate thing to deal with that, but if there’s a way to use gsub and not create a lot of whitespace, that would be helpful to know.

Wait, am I misunderstanding something? From the looks of this, it will do the following:

player.Folder.Food.Value = 'Pizza1Pizza2Pizza3'
local TakeAway, Remainder = player.Folder.Food.Value:gsub('Pizza','')
player.Folder.Food.Value = TakeAway -- 'Pizza'
if Remainder > 1 then -- should be 3
  for i = 1, Remainder - 1 do
    player.Folder.Food.Value  = player.Folder.Food.Value .. 'Pizza' -- 'PizzaPizzaPizza'
  end
end

If this is right, I feel confused on why you’re not just using a table. But to solve your issue for when you only have one pizza:

local TakeAway, Remainder = player.Folder.Food.Value:gsub('Pizza', '')
player.Folder.Food.Value, Remainder = TakeAway, math.ceil(Remainder - .5)
if Remainder >= 2 then
  for i = 1, Remainder - 1 do
    player.Folder.Food.Value = player.Folder.Food.Value .. 'Pizza'
  end
end
1 Like

I ended up going with string.rep, and doing it that way. But your way also worked, and it did fix the issue for when there was a remainder of only 1. Thanks!

1 Like