A Lua Table Sort

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
tdc5013
Prole
Posts: 38
Joined: Wed Feb 08, 2012 4:24 pm

A Lua Table Sort

Post by tdc5013 »

Hey Guys,

I'm working on a card game with AI, and one thing I need to do in the main card selection algorithm is to sort card according to their number. So I have a card object that has things such as Card.Suit, Card.Attribute, and more importantly Card.Number. I've looked at the table sort function and it only seems to give examples on sorting numbers, rather than by object elements. Is there a way to do this? I assumed it will be something along the lines of the given example:

Code: Select all

> t = { 3,2,5,1,4 }
> table.sort(t, function(a,b) return a<b end)
> = table.concat(t, ", ")
1, 2, 3, 4, 5   
But with a change to the comparison function.
User avatar
Nixola
Inner party member
Posts: 1949
Joined: Tue Dec 06, 2011 7:11 pm
Location: Italy

Re: A Lua Table Sort

Post by Nixola »

Code: Select all

cards = {
{x = 1, n = 65},
{x = 2, n = 577},
{x = 3, n = 1}}

sort = function(cardA, cardB)
   return cardA.n < cardB.n
end

table.sort(cards, sort)
The a and b arguments in the sorting function are two element of the table you will sort, so if the table only contain numbers they'll be numbers, if it contains other tables they'll be those tables
lf = love.filesystem
ls = love.sound
la = love.audio
lp = love.physics
lt = love.thread
li = love.image
lg = love.graphics
tdc5013
Prole
Posts: 38
Joined: Wed Feb 08, 2012 4:24 pm

Re: A Lua Table Sort

Post by tdc5013 »

Ok, I understand. I can simply change the given example to:

Code: Select all

table.sort(t, function(a,b) return a.Number<b.Number end)
and I'll get the result I need.

Thanks for the quick reply!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 3 guests