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.
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
--Add new keys:
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.
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)
return tonumber(string.match(a, "INV(%d+)")) < tonumber(string.match(b, "INV(%d+)"))
end)
for index, key in ipairs(order) do
newDictionary["INV"..index] = Dictionary[key]
end
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?).