Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How would i use a table of strings to index a dictionary?

Asked by
abrobot 44
3 years ago
Edited 3 years ago

Say i had a dictionary like this.

local Object = {}
Object.One = {}
Object.One.Two = {}
Object.One.Two.Three = 3

And a table like this.

Directory = {"One", "Two", "Three"}

I would like to run through the table to reference:

Object.One.Two.Three 

I also need to be able to write to the dictionary.

I've looked around and thought about it for a while, but I cant seem to think of a good way to do so. If anyone could help, it would be greatly appreciated.

0
This is confusing and I don't get what you're trying to do sayer80 457 — 3y

2 answers

Log in to vote
1
Answered by
TGazza 1336 Moderation Voter
3 years ago

The above answer is almost there. It doesn't work as the pairs() function returns objects in a list/dictionary in (i think) alphabetical order and Not the way we want.

So the above code would work like:

Object["One"]
-- Next run
Object.One["Three"] -- this would obviously fail as there was no Three nested in the sub dictionary One 

If somehow it passed this error it would then try the leftover value which is Two

The way i would solve this problem is with the following code:

local Object = {}
Object.One = {}
Object.One.Two = {}
Object.One.Two.Three = 3
Object.One.Two.Four = 4

local Dictionary = {"One", "Two", "Three"}
local Dictionary2 = {"One", "Two", "Four"}


function GrabIt(Dict)
    local Curr = Object
    for i=1,#Dict do
        Curr = Curr[Dict[i]]
    end
    return Curr
end
print(GrabIt(Dictionary)) -- prints 3
print(GrabIt(Dictionary2)) -- prints 4

As you see I've made the method a function, it's not necessary to do this, but it makes it easier if you're dealing with multiple dictionaries.

Hope this helps! :)

0
I think this will work but i dont fully understand it yet and i dont have time to test this so im not going to accept it rn, but i will soon. thanks for the help (: abrobot 44 — 3y
0
Oh sorry this doesnt work for me. Yes this will read the right value, but there is still no way for me to write t to the dictionary which i also need to do. abrobot 44 — 3y
Ad
Log in to vote
0
Answered by
nc2r 117
3 years ago
Edited 3 years ago
local Curr = Object
for _, Str in pairs(Dictionary) do
    Curr = Curr[Str]
end
print(Curr)

I believe, though I have not tested it

0
i would tike for the script to read the table and reference the dictionary with the strings not for me to do it manually abrobot 44 — 3y
0
sorry i should have explained that i also need to write to the dictionary and that method doesn't work for that. thanks for trying to help tho. abrobot 44 — 3y

Answer this question