I’ve searched for topics on this problem, however I cannot find the answers i’m looking for.
In my script, I have table with each index being a certain time and the value being another table.
I cannot find a way to sort these “times” from least to greatest.
An example of the table in question is below.
Here’s a module I made a few years ago, as an example:
local SortModule = {}
function SortModule:HighToLow(Table)
table.sort(Table, function(a, b)
return (
a > b
)
end)
end
function SortModule:LowToHigh(Table)
table.sort(Table, function(a, b)
return (
a < b
)
end)
end
return SortModule
local SortModule = {}
function SortModule:HighToLow(Table)
table.sort(Table, function(a, b)
return (
a > b
)
end)
end
function SortModule:LowToHigh(Table)
table.sort(Table)
end
return SortModule
Isn’t this just the LUA table sort function that sorts the values rather than the indexes? It returns this error: “attempt to compare table < table”, which i’m assuming happens because it’s trying to compare the values of the indexes, which are more tables, rather than comparing the index numbers themselves.
you just have to index it back.
Say you have the sorted table of indexes {1, 1.1, 1.5, 2, 3}
you can use ipairs to iterate in order, then use dict[index]
Dictionaries are never guaranteed to return in the same order values are inserted into it. You’d need an array that references each key in the dictionary then sorts the values in the array rather than in the dictionary.
Because your keys are numbers this is pretty easy to do…
local dict = {
[0] = 1,
[1] = 3,
[2] = 5,
[3] = 6,
[0.4] = 2,
[1.3] = 4,
}
-- The part you're interested in
local sortedKeyTable = {}
for k, v in pairs(dict) do
table.insert(sortedKeyTable, k)
end
table.sort(sortedKeyTable)
-- end
-- Then we can check if it worked
for i, v in ipairs(sortedKeyTable) do
print(i)
print(v)
print(dict[v])
print("---")
end
That may be true in some other languages but in lua, a dictionary is literally the same thing as an array. They are both tables, with a key and value for each entry. When indexing them, the order doesn’t even matter, it just finds the value with the matching key.