How to table.sort by a specific sub-entry?

I want to sort a table based on the the value of the “Size” field within it, but I am not sure how to get table.sort() to help out?

tinytable = {} tinytable[1] = { Size=2, Shape=3} tinytable[2] = { Size=3, Shape=2} tinytable[3] = { Size=1, Shape=1}

The most obvious way to sort this would be:

table.sort(tinytable, function(a,b) return a.Size<b.size end><br>However that merely reorders the value of the Size settings without adjusting the rest of the table, ie:<br><br>[code]<br>tinytable[1] = { Size=1, Shape=3}<br>tinytable[2] = { Size=2, Shape=2}<br>tinytable[3] = { Size=3, Shape=1}

Is there a way to compare based on the value (eg: Size) but sort entire {} entries?

(No, function(a.Size,b.Size) does not work. Shucks.)

Thanks again fellas :slight_smile: [import]uid: 41884 topic_id: 13716 reply_id: 313716[/import] </b.size>

cannot be, the above method looks fine.
try the following code and check the result.
[lua]tinytable = {}
tinytable[1] = { Size=2, Shape=3}
tinytable[2] = { Size=3, Shape=2}
tinytable[3] = { Size=1, Shape=1}

for i=1,3,1 do
print(“size :”…tinytable[i].Size…" shape: "…tinytable[i].Shape)
end

print(“sorted”)
table.sort(tinytable, function(a,b) return a.Size < b.Size end)

for i=1,3,1 do
print(“size :”…tinytable[i].Size…" shape: "…tinytable[i].Shape)
end[/lua] [import]uid: 71210 topic_id: 13716 reply_id: 50379[/import]

Argh!! You’re right, of course. But it’s one of those bugs I just couldn’t get my head around until I saw what you said.

  1. I’m using a table converter (making one table out of another) in order to use widget.newTableView (which requires a very specific table structure or it won’t work at all)

  2. I spent so long getting the sort working that I didn’t think to point the display.newText at the new table.

>_<

Thanks!! [import]uid: 41884 topic_id: 13716 reply_id: 50530[/import]