Indexing something by skipping an array?

How could I define the Dragon in a variable without having to index (Egg or Egg2)?

local EggModule = {
	Egg = {
		Rarities = {
			["Dragon"] = 50,
			["Magma"] = 50,
		},
	},
	['Egg2'] = {
		Rarities = {
			["Horse"] = 30,
			["Dog"] = 30,
		}
	}
}

return EggModule

I’m confused by your question. Could you clarify a bit? :slight_smile:

If you’re trying to index ‘Dragon’ in EggModule without having to index Egg or Egg2, there really isn’t a way to do that. You could use a recursive function to iterate over all the tables in EggModule, to look for the given key and return it’s contents.

Really not sure of what you’re trying to accomplish here though.

1 Like
local variable = "A dragon is a large, serpentine legendary creature that appears in the folklore of many cultures around the world."

I just defined a dragon in a variable as you wanted.

1 Like

Tell me if you understand what I mean now. In the code below.

-- v.Name == Dragon.

for _,v in pairs(loc:GetChildren()) do
	if v.Name ~= "UIGridLayout" then
		local Precentage = EggModule["WITHOUT INDEXING EGG"].Rarities[v.Name]
	end
end

Just store a reference to the subtable somewhere.
For example:

local ref = EggModule.Egg.Rarities
ref['Dragon'] = 50

Definition and initialization of ‘Dragon’ variable in EggModule.Egg.Rarities (assuming that it doesn’t exist, if it does then this changes its value to 50).

2 Likes

I’m not sure how that could help me in my situation though. I’m trying to sort LayoutOrder based on the percentages from EggModule. I also like to store the percentages in one place.

function GuiService:Sort(loc, order) -- lock is a table with pets [Dragon, magma & etc]
	if order == "Number" then -- Sorts by number.
		local toSort = {}
		for _,v in pairs(loc:GetChildren()) do
			if v.Name ~= "UIGridLayout" then
				local Precentage = EggModule[ONE OF THE EGGS][v.Name] -- failure
				table.insert(toSort, {data = v, p = Precentage})
			end
		end
		table.sort(toSort, function(a, b)
			return a.p > b.p
		end)
		for i,v in ipairs(toSort) do
			v.data.LayoutOrder = i
		end
	end
end

O, I see that you are using my solution from your another post.
Now I understand what you mean, to do that you need to get the rarity by looping through all eggs until you find the one you’re looking for
Change:

local Precentage = EggModule[ONE OF THE EGGS][v.Name]

to:

local Precentage = 0
for _, egg in pairs(EggModule) do
    if egg.Rarities[v.Name] ~= nil then
        Precentage = egg.Rarities[v.Name]
        break
    end
end
1 Like