Jump to content

Ordering a table by a value in it.


.:HyPeX:.

Recommended Posts

Posted

Hello guys, i want to order a table so that all the rows are in numerical order by the first value of each table. How to do this?

Example:

  
local luaTable = { 
{time="200", acc="crap", name="shit"}, 
{time="300", acc="crap2", name="crapy"}, 
{time="100", acc="crap5", name="shiity"} 
} 
  
local NewTable = orderTable(luaTable, 1} 
  
function orderTable(table,Pos) 
 for i,v in ipairs(luaTable) do 
  if table[i][pos] > table[i+1][pos] then 
  end 
 end 
end 
  
-- It would end something like this: 
  
NewTable = { 
{time="300", acc="crap2", name="crapy"}, 
{time="200", acc="crap", name="shit"}, 
{time="100", acc="crap5", name="shiity"} 
} 
  

the function is just a random wild guessing i'm doing, i've got no clue to what to do here.

Greetz

Posted
You want to sort the table using the 'time' value? if so, use
table.sort 

i tested it but it give's me a error.

attempt to call field 'sort' ( a nil value )

Posted (edited)
table.sort(luaTable,  
    function(a,b)  
        return ( tonumber( a["time"] ) or 0 ) < ( tonumber( b["time"] ) or 0 )  
    end 
) 

Edited by Guest
Posted
local luaTable =  
{ 
    { time = 200, acc="crap", name=":~"}, 
    { time = 300, acc="crap2", name="crapy"}, 
    { time = 100, acc="crap5", name="shiity"} 
} 
  
function orderTable() 
    local tablecache, bigger = luaTable, 0 
    luaTable = {} 
    for i = 1, #tablecache do 
        if tablecache[i].time > bigger then 
            table.insert(luaTable, 1, { time = tablecache[i].time, acc = tablecache[i].acc, name = tablecache[i].name }) 
            bigger = tablecache[i].time 
        else 
            table.insert(luaTable, { time = tablecache[i].time, acc = tablecache[i].acc, name = tablecache[i].name }) 
        end 
    end 
end 

BTW why are you storing time as a string?

Posted
No, i'll save it as a number. This number will be given by the race resource (getTimePassed or smth).

Te pregunte porque lo guardas como un string, no que lo guardes como un string.

Sorry for spanish :P

Posted
No, i'll save it as a number. This number will be given by the race resource (getTimePassed or smth).

Te pregunte porque lo guardas como un string, no que lo guardes como un string.

Sorry for spanish :P

Ah, no idea lel, i was just randomly writing numbers down to give an example xD

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...