Random sorting of a table

Hello, I discovered that tables (not arrays) get sort up randomly, this is a problem for me as my script wont work because of this.
If you did not fully understand what I mean here’s a picture of whats happening:
doc
My output prints this while it should print:
doc2
As you can see the order of table values and keys are totaly messed up.

System Information:
MacBook Pro 2019, MacOS 15.3.0

Expected behaviour:
It should just print and return itself the table provided in the image before.

Frequency: Seldom.
Impact: High.

1 Like

This isn’t a bug dictionaries aren’t ordered

4 Likes

Yeah, if you need to sort a list you are going to have to use an array not a dictionary.

1 Like

Yeah, but if I change key names the sorting is different, most of the times is ordered.

If you really want them ordered, you can do a workaround by utilizing an array.

local Keys = {"Apple", "Pear", "Strawberry", "Plum", "Carrot"}
local Fruits = {
    ["Plum"] = "Red",
    ["Carrot"] = "Orange",
    ["Pear"] = "Green",
    ["Strawberry"] = "Red",
    ["Apple"] = "Red"
}

for _, Key in ipairs(Keys) do
    print(Key, Fruits[Key])
end

It’s the method I’m using, but im using types instead of replicating the key names.

I guess another method that can be utilized is something like the following:

local Fruits = {
    Kinds = {"Apple", "Pear", "Orange"},
    Colors = {"Red", "Green", "Orange"}
}
for n = 1, 3 do
    print(Fruits.Kinds[n], "is the color", Fruits.Colors[n])
end

That way no matter how the two are mis-matched, you’ll have some sort of order to them.

IIRC it’s alphabetical.