I have this simple code that sorts dictionary by keys:
local function sortTableByKeys(t)
local tkeys = {}
for k in pairs(t) do table.insert(tkeys, k) end
table.sort(tkeys)
local result = {}
for _, k in ipairs(tkeys) do result[k] = t[k] end
print(result) --bac
for k, v in result do --abc for some reason
print(k, v)
end
print(result) --still bac???
end
sortTableByKeys({[100] = "a", [1] = "b", [300] = "c"})
When I print out the result, it prints bac as expected, but when I try to loop through it, it returns back to its original state (abc). What is interesting, is that if print result afterwards, it is still going to be bac.
Why this happens and how to fix it?
i messed up with pairs, ipairs and next but it won’t do anything different so just do it like how you sorted it.
local function sortTableByKeys(t)
local tkeys = {}
for k in pairs(t) do table.insert(tkeys, k) end
table.sort(tkeys)
local result = {}
for _, k in ipairs(tkeys) do result[k] = t[k] end
print(result) --bac
for k, v in ipairs(tkeys) do
print(k, t[v])
end
print(result) --still bac
end
sortTableByKeys({[100] = "a", [1] = "b", [300] = "c"})
or optimized:
local function sortTableByKeys(t)
local tkeys = {}
for k in pairs(t) do table.insert(tkeys, k) end
table.sort(tkeys)
local result = {}
for _, k in ipairs(tkeys) do result[k] = t[k]; print(_, k, t[k]) end
print(result) --bac
print(result) --still bac
end
sortTableByKeys({[100] = "a", [1] = "b", [300] = "c"})
The table itself might be sorted, but the way Roblox prints a table might not. That could be what the issue is since you’re directly printing the table. Try sequentially printing each element in a for loop.
local function sortTableByKeys(t)
local keys, values = {}, {}
for i, v in pairs(t) do
table.insert(keys, i)
table.insert(values, v)
end
local function sortFunction(a, b)
return a < b
end
table.sort(keys, sortFunction)
table.sort(values, sortFunction)
for i, v in pairs(keys) do
print(`{v}: {values[i]}`)
end
end
sortTableByKeys({[100] = "a", [1] = "b", [300] = "c"})