How to effectively order this dictionary without changing the way it's structured

I have a table containing all the data for crafting items. Here is a list of all the swords that can be crafted.

[1] = { -- Swords
		Craftable = {
			["500"] = { -- Wooden Sword
				[1] = {
					["19"] = 2, -- Oak Planks
					["280"] = 1 -- Stick
				},
				[2] = {
					["19:1"] = 2, -- Spruce Planks
					["280"] = 1 -- Stick
				}
			},
			["501"] = { -- Stone Sword
				[1] = {
					["1"] = 2, -- Stone
					["280"] = 1 -- Stick
				}
			},
			["502"] = { -- Iron Sword
				[1] = {
					["22"] = 2, -- Iron Ingot
					["280"] = 1 -- Stick
				}
			},
			["503"] = { -- Gold Sword
				[1] = {
					["23"] = 2, -- Gold Ingot
					["280"] = 1 -- Stick
				}
			},
			["504"] = { -- Diamond Sword
				[1] = {
					["24"] = 2, -- Diamond
					["280"] = 1 -- Stick
				}
			},
			["505"] = { -- Emerald Sword
				[1] = {
					["25"] = 2, -- Emerald
					["280"] = 1 -- Stick
				}
			},
		},
		
		Returns = 1,
	},

My problem is they aren’t being displayed in order when I put them in UI. I want whatever item is first, to be displayed as first. I don’t want to change how I arrange the table though. I don’t want to add a bunch more indexs otherwise it’ll just get messy

I think when I had this problem, I had a [“Misc”] category for each item that I used to store random info and the position in which they would appear.

Craftable = {
    ["500"] = {
          ["Position"] = 1
          -- other stuff
    },
    ["501"] = {
          ["Position"] = 2
          -- other stuff
    }
}

Something like this. It’s been a while since I’ve done this so this might not be the exact way I ordered my dictionary.

I can’t do that, as inside that table I have indexed stuff and it needs to stay indexed

["500"] = { -- Wooden Sword
				[1] = {
					["19"] = 2, -- Oak Planks
					["280"] = 1 -- Stick
				},
				[2] = {
					["19:1"] = 2, -- Spruce Planks
					["280"] = 1 -- Stick
				}
			},

I suppose then I would create a list/dictionary inside your ui that would sort through the dictionary. Either you copy paste the the entirety of that dictionary in your local script or you could send it through remotes.

Something like this:

local sortDictionary = {
    ["500"] = 1,
    ["501"] = 2,
    ---etc
}

local order = {}

Then you could add the positions of each into a list that could tell you which order to display, then go through that list to display all the items.

One method might be to use metatables, for example

local NumItems = 1
local Items = {}
setmetatable(Items, {__newindex = function(self, i, v)
    v.Position = NumItems
    NumItems += 1
    rawset(self, i, v)
end})

and then you add the items individually and the position is automatically inserted:

Items["stick"] = {}
Items["tree"] = {}

Hope this helps :slightly_smiling_face: