Using GetAttribute and SetAttribute in a loop sometimes doesn't work

I have a folder with bonuses for the player and I use a function with :GetAttribute and :SetAttribute to adjust the bonus values. This is the code:

for bonus, value in pairs(plrdata.Bonuses:GetAttributes()) do -- remove old support plushie bonuses
	local plushiebonus = plushie:GetAttribute(bonus)
	if plushiebonus then
		plrdata.Bonuses:SetAttribute(bonus, value / plushiebonus)
	end
end

When I call the function in a loop, sometimes this part of the function doesn’t and I can’t figure out why.
For example, when a plushie is equipped the plushies bonus will be multiplied into the current bonus, and divided out when the plushie is unequipped. Unequipping multiple plushies will sometimes cause one of the plushie’s bonuses to not be divided out and the rest of the code in the function runs properly. I think that this has to be the issue because its the only part of my code acting strange and everything else works 100% of the time, whereas sometimes this part will not run.

1 Like

What datatype is the variable bonus?

1 Like

You can use the function typeof or type to verify that the datatypes are correct. If the datatypes are correct, issue a ticket regarding setting attributes.

2 Likes

They are all numbers and I’m setting the correct types. I am getting no errors, the attribute is just not being set for whatever reason. I will see about opening a ticket

2 Likes

If you said that bonus is a number then the function SetAttribute will not work. The variable must be a string.

1 Like

Another problem with the script is that I noticed you are using the GetAttributes function. Are you sure the Instance already has any attributes before you run the loop?

1 Like

When I said they’re all numbers I meant all of the values I’m changing are numbers, bonus is a string and all of the attributes do exist.

My issue is that when I run this code in a loop, this code does not always set the attribute. There are no errors and it does work, just not 100% of the time and I can’t figure out why because its not my code

1 Like

Make sure plushiebonus does not equal to nil or else the if statement will not run.

1 Like

Hey, I have the same issue did you find a solution?