Issue with function to convert array into dict

Hi!

I am trying to make a function that would convert a table of Instances into a Dictionary, where the key would be the name of the instance, to make searching for the item easier. However, for some reason, the return of the function I wrote is a dictionary with nothing in it. The pairs loop does execute, however, because the print statement successfully runs. I’m very confused and wondering if somebody a bit more experienced with lua can help me understand the dictionaries and why this is not working, considering this would be fine in other languages.

function instanceArrToDict(list): boolean	
	local dict = {}
	
	for _, v in pairs(list) do
		print(v.Name)
		dict[v.Name] = dict[v]
	end
	
	return dict
end

local defaultSettings = instanceArrToDict(game:GetService("ServerStorage").Default:GetChildren())

local children = workspace.a:GetChildren()
local dict = instanceArrToDict(children)

for i, v in pairs(defaultSettings) do
	if dict[i] == nil then
		dict[i] = v
	end
end

for i, v in pairs(dict) do
	print(i..": "..v.Value)
end

Thank you!

It’s because when you try to index a blank table with an index that doesn’t exist, it’s going to return nil because it doesn’t exist in your dict table. Essentially what you’re doing here is saying dict[name] = nil

function instanceArrToDict(list): {[string]: Instance} -- this doesn't really matter but this would be what the dictionary looks like
	local dict = {}
	
	for _, v in pairs(list) do
		print(v.Name)
		dict[v.Name] = v -- should be v because v is the instance
	end
	
	return dict
end
1 Like

ahh I see. Awesome goof moment. Thanks lol

1 Like