diffictul situation of ordering objects in a group

I found out that…it works when tried with indexed tables, but since my table use keys instead of indexes, it doesn’t work.

Here is a sample code if u wanna try…

local objList = { } local obj1 = display.newCircle(0,0,0) objList["obj1"] = obj1 local obj2 = display.newCircle(0,0,0) objList["obj2"] = obj2 local obj3 = display.newCircle(0,0,0) objList["obj3"] = obj3 local obj4 = display.newCircle(0,0,0) objList["obj4"] = obj4 local obj5 = display.newCircle(0,0,0) objList["obj5"] = obj5 local obj6 = display.newCircle(0,0,0) objList["obj6"] = obj6 obj1.y =10 obj2.y =40 obj3.y =20 obj4.y =50 obj5.y =60 obj6.y =30 local function sortfn(a, b ) return a.y \< b.y end --no matter if u coment this line or not, function will always produce the same result... table.sort(objList, sortfn) for k,v in pairs(objList) do --objList[i]:toFront() print(objList[k].y) end

RESULTS…

40 30 50 60 10 20

re-read my original post, you missed something important…

>> for k,v in pairs(objList) do

nope – pairs() defeats the whole purpose of sorting a list!, as the order of iteration with pairs() is undefined. you MUST iterate numerically, either with “for i=1,#table” or “for k,v in ipairs(table)” (note the “i” in ipairs, critical difference)

once sorted back-to-front, and iterated in numeric order, toFront() will indeed work.

[EDIT] it occurs to me that THIS is the part you might not “get”:

-- assuming your current list is by alpha keys: local anUnsortableList = ..whatever, your current list as is -- so MAKE a sortable list: local aSortableList = {} for k,v in pairs(anUnsortableList) do aSortableList[#aSortableList+1] = v end -- then sort it local function sortfn(a, b ) return a.y \< b.y end table.sort(aSortableList,sortfn) -- then order your objects in the display for i=1,#aSortableList do aSortableList[i]:toFront() end -- done, no longer need this aSortableList = nil

@davebollinger this is exactly what i wanted…i don’t have words to thank you, i was looking for this for a long time :slight_smile:

I am using it in an enterFrame function so i hope it is ok to do this every frame?

Thanks again!!!