Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua Table Sorting 2 compares

I have gone over as many of the answers here as I could find that had titles I considered near enough to my problem to look into. I haven't seen anyone having my exact issue, so I'm asking a question I hope is just me being ignorant to a simple fact.

I'm trying to code a table that records HP (int) and the distance (boolean) and then sort by HP with only the ones in Range near the top.

local tableTest = {
    {hp = 64, range = true, name="Frank"},
    {hp = 100, range = true, name="Joe"},
    {hp = 2, range = false, name="Jim"},
    {hp = 76, range = true, name="Tim"},
    {hp = 17, range = false, name="Jill"},
    {hp = 16, range = true, name="Phillip"},
}

-- Sort by HP and Range to find lowest Unit in Range.
table.sort(tableTest, function(x,y) return x.hp < y.hp and x.range end)

for i=1, #tableTest do print(tableTest[i].name, tableTest[i].hp) end

The output for this is:

Phillip 16
Jim     2
Frank   64
Jill    17
Tim     76
Joe     100

The output I was expecting from this would be:

Phillip 16
Frank   64
Tim     76
Joe     100
Jim     2
Jill    17

I pray this is just a misunderstanding on my part of how the table.sort works with multiple checks like this (I assumed it was closer to how you declare a variable like this).

edit Additional information - If I change the order of where the range=false indexes are located in the table, the output changes as well (still incorrect). The values just sort themselves into different indexes after the sort.

like image 330
Bubba911 Avatar asked Oct 02 '22 20:10

Bubba911


1 Answers

According to your description, your order function needs to compare range first, then compare hp.

table.sort(tableTest, function(x,y) 
                          if x.range and y.range then return x.hp < y.hp 
                          elseif x.range then return true
                          elseif y.range then return false
                          else return x.hp < y.hp end
                      end)

Maybe there is some shorter version, but this one sure works and the logic is clear.

like image 63
Yu Hao Avatar answered Oct 13 '22 12:10

Yu Hao