luarobloxroblox-studio

Why does roblox studio walk wrong through the table


I am making a game right now in roblox, and need to make gamepass store, however when my loop goes through it (its a table in table), it goes out of order Example code with the tables in table

a = {
    ["5robux"] = {
        value = 10,
        name = "21"
    },
    ["10robux"] = {
        value = 13,
        name = "31"
    },
    ["15robux"] = {
        value = 20,
        name = "41"
    },
    ["20robux"] = {
        value = 25,
        name = "64"
    },
    ["61robux"] = {
        value = 25,
        name = "64"
    },
    ["50robux"] = {
        value = 3,
        name = "64"
    }


}
for i, v in pairs(a) do
    print(i, v)
end

Output:

5robux  ▶ {...}  -  Server - Script:30
50robux  ▶ {...}  -  Server - Script:30
61robux  ▶ {...}  -  Server - Script:30
20robux  ▶ {...}  -  Server - Script:30
15robux  ▶ {...}  -  Server - Script:30
10robux  ▶ {...}  -  Server - Script:30

As you see, it firstly goes to the first element, then to the last and so on

Also tried removing the brackets [], got another output which is still incorrect Output:

robux15  ▶ {...}  -  Server - Script:30
robux5  ▶ {...}  -  Server - Script:30
robux50  ▶ {...}  -  Server - Script:30
robux61  ▶ {...}  -  Server - Script:30
robux10  ▶ {...}  -  Server - Script:30
robux20  ▶ {...} 

How can i fix it, and whats wrong?

Tried changing the loop, but still wrong output


Solution

  • Dictionaries in Lua aren't in order, only arrays are. If you want to be able to iterate over it in the correct order try something like

    a = {
        {
            key = "5robux",
            value = 10,
            name = "21"
        },
        {
            key = "10robux",
            value = 13,
            name = "31"
        },
        {
            key = "15robux",
            value = 20,
            name = "41"
        },
    }
    for i, v in ipairs(a) do
        print(i, v.key)
    end
    

    Which will output this

    1   5robux
    2   10robux
    3   15robux