215 posts
Location
Netherlands
Posted 15 June 2014 - 01:12 PM
Hello everyone!
My question is so simple that the most of you ask why I am asking this, but I am trying to alphabetically sort a table so it is easier searching for something. I am trying to sort the first index on alphabetical order. This is an example of what the table looks like:
data[aspect][1] = 64 --#aspect is a string, the second number indicates how many jars are there and the value is how much of an aspect is in a jar
I tried table.sort, but it is not working. Anyone have ideas?
Edited on 16 June 2014 - 09:33 AM
7508 posts
Location
Australia
Posted 15 June 2014 - 01:19 PM
EDIT: take a look at this
link to also see the code that Bomb Bloke was talking about.
Edited by
7083 posts
Location
Tasmania (AU)
Posted 15 June 2014 - 01:25 PM
You can't really sort the table as it is anyway - keys in the form of strings aren't intended to be retrieved in any sort of order. The strings themselves end up defining the order, and not in a manner that's easily predictable.
I'd take all the key names and shove them in a numerically indexed table, then table.sort()
that. Funnily enough, that's what the script linked from
here was crashing on (if only because Dire's code was getting unexpected results from a certain peripheral call).
215 posts
Location
Netherlands
Posted 16 June 2014 - 11:32 AM
Thanks for the good responses everybody! It made me think of how I need to sort the table and I came up with a solution that is quite obvious, but still genius. This is a snippet of what I made on codepad:
Spoiler
data = {}
toBeSorted = {}
data["Aer"] = {}
data["Aer"][1] = 33
data["Aer"][2] = 12
data["Aer"][3] = 63
data["Herba"] = {}
data["Herba"][1] = 44
data["Herba"][2] = 42
data["Herba"][3] = 33
data["Fabrico"] = {}
data["Fabrico"][1] = 21
data["Fabrico"][2] = 12
data["Fabrico"][3] = 22
data["Aqua"] = {}
data["Aqua"][1] = 22
data["Aqua"][2] = 44
data["Aqua"][3] = 55
for k,v in pairs(data) do
toBeSorted[#toBeSorted + 1] = k
end
table.sort(toBeSorted)
for k,v in pairs(toBeSorted) do
print(k..": "..v)
end
--#Output
--# 1: Aer
--# 2: Aqua
--# 3: Fabrico
--# 4: Herba
7083 posts
Location
Tasmania (AU)
Posted 16 June 2014 - 11:39 AM
By the by, you could cut down that initial table declaration somewhat:
data ={["Aer"] = {33,12,63}, ["Herba"] = {44,42,33}, ["Fabrico"] = {21,12,22}, ["Aqua"] = {22,44,55}}
215 posts
Location
Netherlands
Posted 16 June 2014 - 12:04 PM
-snip-
The making of that table is automated, so it doesn't matter.
Edited on 16 June 2014 - 10:17 AM