Sorting Tables

You can sort tables by one or more field using the TB.Sort() function. Here is a simple example that shows how you can use sort your tables using various sorting methods :

Function TB.TEST_Sort()
  Local table = { { name = "Spiderman", power = "Web" },
                  { name = "Thor"     , power = "Hammer" },
                  { name = "Flash"    , power = "Speed" },
                  { name = "Iron Man" , power = "Armour" },
                  { name = "Iron Man" , power = "Weapons" },
                  { name = "Hulk"     , power = "Strenght" } }
                  
  NPrint("TABLE CONTENT")
  For i = 0 To 5
    Local v = table[i]
    NPrint("[color=#yellow]" .. v.name .. "[/color] " .. v.power)
  Next
  
  NPrint("\nSORTED by Name (descending order)")
  TB.Sort(table, True, "name", Nil, "quicksort")
  For i = 0 To 5
    Local v = table[i]
    NPrint("[color=#yellow]" .. v.name .. "[/color] " .. v.power)
  Next
  
  NPrint("\nSORTED by Power (ascending order)")
  TB.Sort(table, False, "power", Nil, "combsort")
  For i = 0 To 5
    Local v = table[i]
    NPrint("[color=#yellow]" .. v.name .. "[/color] " .. v.power)
  Next
  
  NPrint("\nSORTED by Name & Power (descending/descending order)")
  TB.Sort(table, { True, True }, { "name", "power" }, Nil, "quicksort")
  For i = 0 To 5
    Local v = table[i]
    NPrint("[color=#yellow]" .. v.name .. "[/color] " .. v.power)
  Next

  NPrint("\nSORTED by Name & Power (descending/ascending order)")
  TB.Sort(table, { True, False }, { "name", "power" }, Nil, "quicksort")
  For i = 0 To 5
    Local v = table[i]
    NPrint("[color=#yellow]" .. v.name .. "[/color] " .. v.power)
  Next
  
  NPrint("\nLeft mouse to QUIT.")
  
  WaitLeftMouse()
EndFunction
hollywoodlibs/tables/testsort.txt · Ultima modifica: 2016/10/21 15:46 da admin
CC Attribution-Noncommercial 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0