Search code examples
lualua-table

Do not lose reference to a table in a recursive function in Lua


I have a table that is dynamic, it can contain tables within another, I need a recursive function to help me specifically find a key and when it finds it, to be able to make changes and have these changes reflected in the first reference of the table.

My table:

local table = {
    tablePlayer = {
        ["Volcam"] = "Druid",
        ["Chaman King"] = "Paladin"
    }
}

My recursive function

local function func(t)
    for k, v in pairs(t) do
        if type(v) == "table" then
            return func(v)
        else
            if k == "Volcam" then
                v = "Master"  -- CHANGE VALUE
            end
        end
    end
end

func(table) -- call function

I would like not to lose reference to the table and that the changes are reflected when the recursive function ends

print(table.tablePlayer.Volcam) -- Print: Druid, expected print: Master 

Solution

  • Using v = "Master" only changes the value of the local variable, but not the value in the table you want to change. Replace it with t[k] = "Master" and you should get the expected result.