Table Indexing Problem

Hey guys, so I have a problem indexing tables. I’m gonna try my best to explain because this may be a bit confusing.




local t = {g = {h = {f = 2}}}

local function Index(IndexPathway, desiredvalue, MainTable)
	
  --Not sure what to write.
	
end

Index({"g", "h", "f"}, 5, t)

So I have a index pathway. What I want the function to do is index the table called " t " and change the value of " f " automatically. I will just have to give the path and the script will change the value of the last pathwaypoint.

So my path is {"g", "h", "f"}, my last pathwaypoint would be f. Which as you can see is there on table " t ". How would I automatically index the table " t " with this pathway and change the value of " f " in the table " t "

If your still confused I would be happy to answer any questions.

Thanks for reading, any help is greatly appreciated! :slight_smile:

You could probably do something like this:

local t = {g = {h = {f = 2}}}

local function Index(IndexPathway, desiredvalue, MainTable)
    local temp = MainTable
    for Index = 1, #IndexPathway - 1 do
        temp = temp[IndexPathway[Index]]
    end
    temp[IndexPathway[#IndexPathway]] = desiredvalue
end

Index({"g", "h", "f"}, 5, t)
1 Like

Thanks, that worked! I’m trying to understand what you did now.

1 Like

Hey, so I understand everything in the function except this one line:

    temp[IndexPathway[#IndexPathway]] = desiredvalue

When you set the value of that index to the desired value how does that effect the main table? I mean it works, but I’m not sure why it exactly works. Could you explain?

The for loop gets the table that contains the table around the final index, storing it in temp

So if you had

{g = {h = {f = 2}}}
The for loop would store it in temp
temp = {g = {h = {f = 2}}}
Then it would peel off one layer…
temp = {h = {f = 2}}
…then another
temp = {f = 2}
And at this point it stops, because theres only one index left
If you took off another layer, you would have only a number, 2

You cant set the value of a number and have it effect t, you have to change the value of the table
This is why it stops
(Its a similar concept to if you did
local a = 1
local b = a
b = 2
^This does NOT affect a in any way

This however does
local a = {1}
local b = a
b[1] = 2
)

This is why the loop stops before it peels off the final layer
It takes temp, which at this point is {f = 2}, and then takes the final provided index, “f”, and sets that to the desired value

Ohhhh, that makes a lot more sense. Thanks for the help!

1 Like