There isnāt really an automatic way to do it because Roblox doesnāt know what āfirstā, āsecondā or āthirdā means. Itās just a random string of text that humans are able to read.
You can do it with tables and string manipulation though. It isnāt as easy as table.sort as you are using nested tables but hereās one way to go about it:
local suffixes = { -- We need to write these out manually
[1] = 'first';
[2] = 'second';
[3] = 'third';
[4] = 'fourth';
[5] = 'fifth';
[6] = 'sixth';
[7] = 'seventh';
[8] = 'eighth';
[9] = 'nineth';
[10] = 'tenth';
}
local numbersToSort = {} -- create a temporary folder for numbers to sort
for i,v in pairs(a) do
numbersToSort[#numbersToSort + 1] = (suffixes[v[1]]) -- insert the number to save for after
end
a = {} -- we want to overwrite the table to a new one.
for i,v in pairs(numbersToSort) do
a[suffixes[i]..'value'] = {i} -- create the new entry in the a table
end
print(a)
--[[ Should output:
{ ['firstvalue'] = {1};
['secondvalue'] = {2};
['thirdvalue'] = {3} }
]]
Read this article for more information about table and table.sort: table | Roblox Creator Documentation. Also, it does not make sense to only store one value in a table. Perhaps you can rewrite your table like this:
local a = {
firstvalue = 3,
secondvalue = 2,
thirdvalue = 1,
}
The test code provided just prints keys in undefined order and the address of the table. table.sort only sort indexes that are integers: https://www.lua.org/source/5.1/ltablib.c.html#auxsort. Most methods in table only accounts for integer indexes.
Why are you even setting up your code in this way? What are you using it for? Can you not use
local a = {
[3] = "firstvalue",
[2] = "secondvalue",
[1] = "thirdvalue",
}
and then iterate through it in an ipairs loop?
Or iterate to 1 backwards from three and subtract four by the current i + 1?
for i = 3,1,-1 do
local index = (4 - i)
print(index)
end
or just iterate normally?
for i = 1,3 do
print(i)
end
Anyways, now that Iāve gotten my questioning out of the way, you are not able to sort dictionaries because they do not use the same indexing as arrays do. I recommend checking out this resource:
Alright, I wracked my brain, and the solution is simple. You must iterate through it twice. Please understand however that this will not sort the dictionary but will give you the keys you want in order during iteration.
local function IterateWierdDict(dict)
local i = 1
for _,value in pairs(dict) do
for k,v in pairs(dict) do
if i >= 4 then
break
end
if v[1] == i then
i += 1
-- Your code that you want to execute in order
end
end
end
end
However, if this does not suit your fancy I recommend organizing your table in a simpler manner.