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.
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! :)
local Curr = Object for _, Str in pairs(Dictionary) do Curr = Curr[Str] end print(Curr)
I believe, though I have not tested it