# How I can shift indexes, so they will be IND1, IND2, IND3

Hello guys. I want to make dictionary sort system, which should make from this:

local Dictionary = {
INV3 = "Hi",
INV4 = "I'm",
INV6 = "Very",
INV9 = "Hard",
INV10 = "Problem",
}

To this:

local Dictionary = {
INV1 = "Hi",
INV2 = "I'm",
INV3 = "Very",
INV4 = "Hard",
INV5 = "Problem",
}

This not hard question made me struggle for 3 days… Can someone please me give idea, how I can implement this system?
Note: Value can be anything, not string only.

5 Likes

One way to approach this problem is to just use table.sort

You would have to develop your own heuristic on what makes the items “sorted” since you are using custom values and not just a numerical array. You can define a custom function to do that for you and pass it into the sort method.

--Isolate the values:
local values = {}
for key, value in pairs(Dictionary) do
table.insert(values, value)
--Remove the old key:
Dictionary[key] = nil
end

for i, value in pairs(values) do Dictionary["INV"..i] = value end

--View the dictionary:
print(Dictionary)

Edit: This reply is false and doesn’t keep the table order, for the right reply please check the solution @msix29 has given below.

3 Likes

This is a good way of doing this but there is unnecessary loops.

--decalring table and an index
local Dictionary, Index = {...}, 1

for key, value in Dictionary do
-- remove the key and the value it self
Dictionary[key] = nil

-- directly insert the value
Dictionary["INV"..(Index)] = value
Index += 1
end

Solutions above were unsuccessful, indices’ order is not maintained. (@NyrionDev @kalabgs)
Here’s a solution maintaining the order.

local Dictionary = {
INV3 = "Hi",
INV4 = "I'm",
INV6 = "Very",
INV9 = "Hard",
INV10 = "Problem",
}

local newDictionary = {}
local order = {}

for key, value in pairs(Dictionary) do
table.insert(order, key)
end

table.sort(order, function(a, b)
end)

for index, key in ipairs(order) do
newDictionary["INV"..index] = Dictionary[key]
end
4 Likes

Dictionary order in Lua is not guaranteed. So, using a dictionary, this is technically not possible.

You will have to store the values in an array instead.

1 Like

You are right but your solution does not actually change the iteration too.

Mine sorts them so the lowest n (INVn) corresponds to INV1 and the 2nd lowest corresponds to INV2 which is, as far as I can see, what he wants.

@sleitnick I’m pretty sure he only needs the indices to be arranged in order (1, 2, 3…) instead of something like (1, 5, 9…), if not then what you said would be the solution to this problem (kinda of?).

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