ESOUI

ESOUI (https://www.esoui.com/forums/index.php)
-   General Authoring Discussion (https://www.esoui.com/forums/forumdisplay.php?f=174)
-   -   Sorting a table in lua (https://www.esoui.com/forums/showthread.php?t=1680)

McGuffin 05/30/14 12:44 PM

Sorting a table in lua
 
Hi, i am trying to figure how to sort a table with multiple entries

Here is my problem.
I have something like that
Code:

tArray["name1"] = { param1 = 10, params2 = 20, param3 = 50}
tArray["name2"] = { param1 = 5, params2 = 45, param3 = 132}
tArray["name3"] = { param1 = 8, params2 = 55, param3 = 10}

now i want to sort tArray, by using the param1 order.
so i tried somthing like that
Code:

function sortParam1(a,b)
  return a[1]<b[1]
end

table.sort(tarray, sortParam1)

but that doesnt work...
is everyone know a way to do this?

stjobe 05/30/14 12:57 PM

lua.org has something to say on the issue.
As has the lua-users.org wiki.
And even Stack Overflow.

lyravega 05/30/14 12:58 PM

Uhm, I don't know if table.sort works for tables; I think it only works for arrays (tables with numeric keys in order, 1...n). Don't take my word on it though.

The other thing is, in your function, it says "a[1]<b[1]", but what is a[1]? Shouldn't it be a.param1?

McGuffin 05/30/14 01:13 PM

Quote:

Originally Posted by stjobe (Post 8821)

well, i ve already found every links you provide (and even more).
but none of them is an answer to my question (they are all related to array with a single params), and this is why I am asking here.


Quote:

Originally Posted by lyravega (Post 8822)
Shouldn't it be a.param1?

That was my first thought , and that doesnt work either, this is why I tried a more direct way with the index ...
this is tricking me ;) i know how to do that in delphi or c++ but not in lua...

SinusPi 05/30/14 01:41 PM

There's no way to do that, simply. Your table isn't even sorted by the keys, not to mention the value of the param1 attribute.

But, you can do something else.

Code:

tArray={}
tArray["name1"] = { param1 = 10, params2 = 20, param3 = 50}
tArray["name2"] = { param1 = 5, params2 = 45, param3 = 132}
tArray["name3"] = { param1 = 8, params2 = 55, param3 = 10}

bag = {}
for k,v in pairs(tArray) do
  table.insert(bag,{key=k,data=v})
end

table.sort(bag,function(a,b) return a.data.param1<b.data.param1 end)

for i,t in ipairs(bag) do
  print(t.key)
end


McGuffin 05/30/14 02:07 PM

thank you SinusPi, it works like a charm ^^

stjobe 05/30/14 02:38 PM

Quote:

Originally Posted by McGuffin (Post 8824)
well, i ve already found every links you provide (and even more).
but none of them is an answer to my question (they are all related to array with a single params), and this is why I am asking here.

I'm happy you got your answer, and I'm sorry I came off as a bit ... "RTFM, dude". Not my intention :)


All times are GMT -6. The time now is 05:25 PM.

vBulletin © 2024, Jelsoft Enterprises Ltd
© 2014 - 2022 MMOUI