Getting number from table entry

How do I get a number from a table entry? So far, I have it so it loops through the table but I was hoping there was an easier method that didn’t rely on a loop every time.

I want to retreive “Weight” from the enemies with “Name”, for example I want to be able to access the weight from:
{Name = “Power 1”, Weight = 1000, Tier = “Common”}

Table setup:

local Items = {
	Common = {
		["Weight"] = {Weight = 1000}, 
		 {Name = "Power 1", Weight = 1000, Tier = "Common"}, 
	},
	Standard = {
		["Weight"] = {Weight = 600},
		 {Name = "Power 2", Weight = 600, Tier = "Standard"},
	},
	Rare = {
		["Weight"] = {Weight = 50},
		 {Name = "Admin Power", Weight = 50, Tier = "Rare"},
	},
	LivingMyth = {
		["Weight"] = {Weight = 10},
		 {Name = "Power 3", Weight = 10, Tier = "Living Myth"},
	},
}

So far I used two pairs loops that would loop through the table and then loop through the results of that loop, picking out anything under “Weight” as weight will only ever have one number.

1 Like

I would try table.find(). I think that it will work.

1 Like

As far as lopping you can just make a function to use instead of writing it out

function Items:GetWeightByName(name :string) :number?
	for rarity, groupItems in pairs(Items) do
		for _, item in pairs(groupItems) do
			if item.Name == name then 
				return item.Weight
			end
		end
	end
end

If you construct the table differently, something like this :

local Items = {
   Common = {
      ["Weight"] = 1000;
      ["Info"] = {Name = "Power 1"; Weight = 1000; Tier = "Common"}
   }
}

Then you could get the Weight by this:

local weight = Items.Common.Info.Weight
1 Like