Dictionary Keys not working

I am trying to make a for loop that cycles through information stored in a module script, checks if the index value has the key “Weight” associated with it, then if so, adds the value of its weight to a separate table. The only issue is that I am trying to exclude the value associated with “Decoration Density”, but everything I have tried is not working. I feel like this is something really straight forward that I am not seeing, I am not very experienced when it comes to using dictionaries.

Here’s the module script that contains the information:

local DecorationInfo = {
	
	["Decoration Density"] = 10,

	["Grass"] = {

		["Weight"] = 150

	},

	["Flower"] = {

		["Weight"] = 3

	}

}

return DecorationInfo

And here’s the script that has the for loop:

local Weights = {}
local DecorationInfo = require(script.DecorationInfo)

for Item, Entry in pairs(DecorationInfo) do
	
	if Item["Weight"] then
		
		table.insert(Weights, Item["Weight"])
		
	end
	
end


Let me know if you have any questions! Any help is appreciated.

local Weights = {}
local DecorationInfo = require(script.DecorationInfo)

for Item, Entry in pairs(DecorationInfo) do
	if type(Entry) == "table" and Entry["Weight"] then	
		table.insert(Weights, Entry["Weight"])	
	end
end

Wow! That did it. What was the problem in my initial code?

Well, when you’re looping you have the Item and Entry as the variables right? The Item is a string while the Entry is the actual value.

So the loop goes like this:
Item: Decoration Density, Entry: 10
Item: Grass, Entry: {Weight = 150}
Item: Flower, Entry: {Weight = 3}

As you can see, doing Item[“Weight”] wouldn’t work, because Item is a string, and you can only index tables. If Item is Grass, doing “Grass”[“Weight”] wouldn’t really make sense, while doing {Weight = 150}[“Weight”] would get you the value of 150. Hope this helps.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.