Dictionary Orders Getting Mixed Up

Hello! Whenever I loop through this dictionary the output is not in the right order. I have tried adding alphabetical ordering and se string manipulation, but it is still random. All help appreciated!

	local classes = {
			["a.sword"] = {},
			["b.armor"] = {},
			["c.relic"] = {},
			["d.cosmetic"] = {},
			["e.blade"] = {},
			["f.handle"] = {},
			["g.pommel"] = {},
			["h.material"] = {},
		}

Here is the output -
image

It is not guaranteed that the order of keys in a dictionary will be the same as the order of elements in an array.

A solution would be creating separate arrays, one for key names and one for values/tables.

1 Like

Sorry I’ not 100% sure on what you mean by separate arrays. Could you show me a quick example? Thanks

I don’t think you can use an order for a dictionary, an alternative is:

local classes = {
	{name = "a.sword"},
	{name = "b.armor"},
	{name = "c.relic"},
	{name = "d.cosmetic"},
	{name = "e.blade"},
	{name = "f.handle"},
	{name = "g.pommel"},
	{name = "h.material"},
}

-- then using ipairs
1 Like

You can split that dictionary into two so it will be like two arrays. One array holding the keys, and another holding the values.

local Keys = {
    "a.sword",
    "b.armor",
    "c.relic",
    "d.cosmetic",
    "e.blade",
    "f.handle",
    "g.pommel",
    "h.material",
}

local Values = {
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
}

for KeyIndex, KeyName in ipairs(Keys) do
    local ItsValue = Values[KeyIndex]
    print(KeyName, ItsValue)
end
1 Like

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