I made a table that contains default setting,
like this :
local DefaultSettings = {
PC = {},
Gamepad = {},
Mobile = {},
Others = {},
}
And i making SettingUI and trying to use loop for building some buttons.
like this :
local Order = 0
for key, value in pairs(DefaultSettings) do
local Button = Instance.new("TextButton")
Button.Name = key
Button.Position = UDim2.new(0, Order*10, 0, 0)
Order += 1
end
and the result of order is : [ Mobile PC Others Gamepad ].
as more easy to see :
local DefaultSettings = {
PC = {},
Gamepad = {},
Mobile = {},
Others = {},
}
for key, value in pairs(DefaultSettings) do
print(key) -- Prints [ Mobile → PC → Others → Gamepad ]
end
print(DefaultSettings) --[[ Prints
{
["Gamepad"] = {},
["Mobile"] = {},
["Others"] = {},
["PC"] = {}
}
]]
I have no idea WHAT happend on my table order
Is there any way to sort pairs order?
I have tried table.sort but as the key is not number, it is not working.
I wanna keep my table variant and pairs loop script…
dictionaries aren’t meant to have any sort of order.
Arrays are structured like:
1 = One
2 = Two
3 = Three
And functions iterate by this index. Dictionaries instead of it use strings, and due to this it’s impossible to sort them in some way.
I don’t know of any other straight-forward way to create sorted dictionaries without storing the initial table in an array, since, according to the Roblox Creator Documentation site, dictionaries are not sorted when looping over it:
Unlike using ipairs() on an array, using pairs() on a dictionary doesn’t necessarily return items in the same order that they’re in the dictionary.
If you’d like to:
Retain the original format in some way (having the type of device act as the key and the table of settings as the value)
Make minimal changes to the existing code
Ensure it’s organized in the order that you intended
And improve its readability in the new format (without needing the device type as the first value for each of the settings tables)
then, you could create an additional table that has the sole purpose of defining which indexes correspond with which settings table:
local SettingsIndexes = {
[1] = "PC",
[2] = "Gamepad",
[3] = "Mobile",
[4] = "Others"
}
local DefaultSettings = {
[1] = {},
[2] = {},
[3] = {},
[4] = {}
}
---
local Order = 0
for index, value in DefaultSettings do
local Button = Instance.new("TextButton")
Button.Name = SettingsIndexes[index] --[[ With the current index of the
"DefaultSettings" table, it looks through the "SettingsIndexes" table,
which contains a string that corresponds with the name of the device type --]]
Button.Position = UDim2.new(0, Order * 10, 0, 0)
Order += 1
end