Inserting new values into dictionaries then for loops don't work

  1. What do you want to achieve?
    So, I’m using a for loop to go though a dictionary, I’d like it to lower the value of them all by 1.

  2. What is the issue?
    Because I’m adding new values to the dictionary afterwards it only lowers the values that are already put in there by 1, rather than the new ones.

  3. What solutions have you tried so far?
    From what I’ve seen I have to use metatables, but I have absolutely no idea how to use them. I’ve been through some previous posts and community tutorials, but I’m not really understanding what I should be doing here.

Any help is much appreciated :slightly_smiling_face:

You can put the new values in a temporary table, and when you run the for loop to lower the values by 1, lower the values in the temporary table as well. Then, you can append all the data from the temporary table to the main table.

1 Like

Wouldn’t that create the same problem? When you lower the values by 1 in the main table then try and lower them again, it wouldn’t work, correct?

When you append values to the main table, you’ll be able to lower them, as long as you keep your table saved. You should post the code where you are dealing with these tables, so I can see more specifically what the issue is.

1 Like

Ohhh, alright, I see how that works now. Here is what I did:

for Key,Value in pairs(MainTable) do
	if Value ~= 1 then
		TempTable[Key] = Value - 1
		MainTable[Key] = TempTable[Key]
		TempTable[Key] = nil
    end
end

That should work, and you’ll be able to check the main table whenever needed as well.

1 Like

Yep, everything is working perfectly. Thank you for your help, I was making that way more complicated than it needed to be.