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

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

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.

1 comment

0

This is confusing and I don't get what you're trying to do

2 answers

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! :)

2 comments

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 (:

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.

local Curr = Object
for _, Str in pairs(Dictionary) do
	Curr = Curr[Str]
end
print(Curr)

I believe, though I have not tested it

2 comments

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

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.

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