Reindexing a table

Sometimes it is very useful to have a function able to reindex a table, reindexing a table is something like this:

Table contents

index content
alpha{ name = “Jhon”, type = “Medic” }
beta{ name = “Ted”, type = “Soldier”}
gamma{ name = “Ryan”, type = “Scientist}

You want to reindex the table on column name so you want to get:

index content
Jhon{ code = “alpha”, type = “Medic” }
Ted{ code = “beta”, type = “Soldier”}
Ryan{ name = “gamma”, type = “Scientist}

Using the TB.Reindex() function it is very easy to achieve.

Function TB.TEST_ReIndex()
  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("INDEX : [color=#red]" .. i .. "[/color], NAME : [color=#yellow]" .. v.name .. "[/color], POWER : " .. v.power)
  Next

  NPrint("\nReindexing by power")
  Local table = TB.ReIndex("id", "power", table)
  For i, v In Pairs(table)
    NPrint("INDEX : [color=#red]" .. i .. "[/color], NAME : [color=#yellow]" .. v.name .. "[/color], ID : " .. v.id)
  Next
  
  NPrint("\nReindexing by name")
  Local table = TB.ReIndex("power", "name", table)
  For i, v In Pairs(table)
    NPrint("INDEX : [color=#red]" .. i .. "[/color], POWER : [color=#yellow]" .. v.power .. "[/color], ID : " .. v.id)
  Next
  NPrint("[b][color=#blue]>> ONE RECORD <IRON MAN> AS BEEN DELETED <<[/color][/b]")

  NPrint("\nLeft mouse to QUIT.")
  
  WaitLeftMouse()
  
EndFunction

If you run the example you can see that it could be a problem with items with the same index because they are overwritten, infact if you have:

index content
alpha{ name = “Jhon”, type = “Medic” }
beta{ name = “Jhon”, type = “Soldier”}

And you reindex the table on the 'name' column you will get only one entry:

index content
Jhon{ code = “beta”, type = “Soldier”}

That's because the index must be unique.

hollywoodlibs/tables/testreindex.txt · Ultima modifica: 2016/10/21 09:07 da admin
CC Attribution-Noncommercial 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0