Updating Table Values in Loops

  1. What do you want to achieve?
    I want to create a function to adjust player stats based on an argument passed as opposed to a separate function for each stat. I have included a snippet of the code below.

  2. What is the issue?
    The greyed out code is working correctly, but the second block of code is printing the level update from 1 to 2. then keeps printing 2. It doesn’t seem to be saving to the data store correctly.

  3. What solutions have you tried so far?
    I’ve watched various profile service tutorials, searched the dev hub and tried asking in various discord groups.
    I don’t think I understand the logic when converting

profile.Data.playerBaseStats.level += amount 

to

profile.Data.playerBaseStats.*ArgumentPassed* += amount 

I thought the playerBaseStats was a dictionary containing the [“StatName”] = value, so I tried to update the value in the dictionary, but I don’t believe profile service saves the data in the same way I initialize it.

--[[function module.AdjustLevel(player: Player, amount: number)
    local profile = module.Profiles[player]
    if not profile then return end

    profile.Data.playerBaseStats.level += amount
    RemoteEvents.Level:FireClient(player, profile.Data.playerBaseStats.level)
end
]]--

function module.AdjustPlayerBaseStats(player: Player, stat: string, amount: number)
    local profile = module.Profiles[player]
    if not profile then return end
    
    local playerBaseStats = profile.Data.playerBaseStats
    
    for i,v in pairs(playerBaseStats) do
        if i == stat then
            v += amount
            print(i.." "..v)
        end
    end
end
1 Like

Change

To:

You can’t change a loop variable, since it’s just a copy of the actual value.

1 Like

Thank you @isPauI that worked perfectly!

Are you able to explain or provide a link to some documentation further explaining the solution?

Sure, here are some links that should help you understand this case more:
https://www.lua.org/pil/4.3.4.html

In your case, v is a copy of the Stat value that only exists inside the loop, so changing it only affects it for that iteration, and it’s not the actual data that you want to change.
By doing playerBaseStats[i], you refer to the actual value that’s declared outside the loop.

1 Like

Awesome, I appreciate the additional info.
The link provided let me find the more on the topic (mostly the same principle but worded differently). I will share an additional link in case anyone in the future finds this thread helpful.

I haven’t tried it yet, but logically I could replace [i] with [stat] for the same result in isPaul’s solution.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.