Jump to content

Ordering a table by a value in it.


.:HyPeX:.

Recommended Posts

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

Link to comment
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?

Link to comment

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...