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?

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

cannot be, the above method looks fine.
try the following code and check the result.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

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!!

views:1683 update:2011/9/27 18:14:54
corona forums © 2003-2011