Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Can you edit a table with recursion?

I have a function that goes through a table recursively to find a key, then changes the key's value. However, despite the function running without error, and the print statements in the middle printing what I expect, the values within the original table aren't changed. I feel like the values the script is altering aren't the actual values from the original table.

function dataManager.setStat(player, statName, newValue)
    local statFound = false
    local function recursiveIteration(curTable)
        for key,value in pairs(curTable) do
            if key == statName then
                print(key , " = " , value)
                statFound = true
                value = newValue
                print(key , " = " , value)
            elseif type(value) == "table" then
                recursiveIteration(value)
            end
        end
    end
    waitForSessionStats(player)
    recursiveIteration(sessionStats[getScope(player)])
    return statFound
end

I get the output statName = oldValue statName = newValue

But the original table's values don't change.

1 answer

Alright had to get some sleep but then I figured out what I was doing wrong.

value = newValue isn't the correct way of setting a value (this is what coding late at night gets me).

curTable[key] = newValue is what I should have been doing. value is just a search index, so I wasn't doing anything to the table at all by changing the search index to newValue. Going back and getting curTable then indexing curTable[key] and setting that to newValue changed the original table for me.

This discussion is preserved as it was. New answers, comments, and votes are closed.