Page 1 of 1

Sorting Tables of Tables

Posted: Sat Mar 19, 2011 7:57 pm
by Kingdaro
I am very frustrated trying to find a function that won't make my tiles in my isometric game look like this:
ARRRRRGH.png
ARRRRRGH.png (4.33 KiB) Viewed 1974 times
The game draws the tile images via a table of tables, as the title states:

Code: Select all

sX = 0
sY = 0
tiles = {}

grass = love.graphics.newImage("grass.png")
forest = love.graphics.newImage("forest.png")

table.insert(tiles,{grass,0,0})

table.insert(tiles,{forest,0,1})
table.insert(tiles,{forest,0,-1})
table.insert(tiles,{forest,1,0})
table.insert(tiles,{forest,-1,0})

function love.draw()
	for i,v in pairs(tiles) do
		local img = v[1]
		local x = v[2]
		local y = v[3]
		
		love.graphics.draw(img,
		(sX+(x*28)+(y*28))+(400-32),
		(sY+(x*14)+(y*-14))+(300-32)
		)
	end
end
And I need a function that will sort the tables by the third value, greatest to least, and the tables that have equal third values will be sorted by their second values,least to greatest. Example:

{grass,0,3}
{grass,0,2}
{grass,3,1}
{grass,4,1}
{grass,5,1}
{grass,0,0}

I just can't seem to find the right math to do this, and it'd be cool if someone could help me. ^^

Re: Sorting Tables of Tables

Posted: Sat Mar 19, 2011 8:23 pm
by BlackBulletIV

Code: Select all

table.sort(tiles, function(a, b)
  return b[3] < a[3]
end
The table.sort function is your friend. The function tells it how to deal with two items in the table. To quote from Programming in Lua:
This order function receives two arguments and must return true if the first argument should come first in the sorted array.

Re: Sorting Tables of Tables

Posted: Sat Mar 19, 2011 8:47 pm
by Kingdaro
The solution you gave alone wasn't satisfiable, but I screwed around with it and got the desired result. Thanks. ^^

Re: Sorting Tables of Tables

Posted: Sat Mar 19, 2011 10:58 pm
by BlackBulletIV
What went wrong with it?

Re: Sorting Tables of Tables

Posted: Sun Mar 20, 2011 12:52 am
by Taehl
I had this same problem a long, long time ago. Except, Isome has its tiles in three dimensions, making things even trickier.

Re: Sorting Tables of Tables

Posted: Mon Mar 21, 2011 1:26 am
by Jasoco
Is there any reason you're not using a grid?

Code: Select all

tile = {}
for x=0,map_width-1 do
  tile[x] = {}
  for y=0,map_height-1 do
    tile[x][y] = tile_data
  end
end
Then you wouldn't need sorting as you'd just draw from 0,0 to map_width,map_height by looping through the same way.

Code: Select all

for x=0,map_width-1 do
  for y=0,map_height-1 do
    --draw tile here
  end
end
You'd only have to sort objects like characters that can move around the map by their Y value.

Of course drawing the tiles and translating the X and Y's to isometric coordinates would require some more math...