Search code examples
luanested-loops

LUA and table data - finding data in a nested loop


I have the following table

scavenging = 
{
  {
    type = "Greenskin|16",
    fast_levelup = 20,        --Number of levels with 75% chance to level up after required level
    normal_levelup = 40,      --Number of levels with 50% chance to level up after fast_levelup + required level
    slow_levelup = 40,        --Number of levels with 25% chance
    drops =                   --Drops
    {
      {items = {"Linen", "Bolt of Linen", "Coarse Thread", "Feather", "Cotton"}, droprates = {60, 10, 10, 10, 2}},
    },
  }, 
}

This is one data value in a series. I use

function scavenge_meta(scavenge_name)
    for _, meta in pairs(scavenging) do
        if string.match(meta.type, scavenge_name) then
            return meta
        end
    end
end

to pull the needed data. The question is, is there an easy way to get to the droprates value without having to do a few for (pairs)? Right now for example I can use:

local founditem = scavenge_meta("Greenskin|16")

And this works, and then I can use founditem.fast_levelup etc. I was hoping to access the drops table with founditem.drops.items for example, but this doesn't work, I need to do a pairs(founditem.drops) then pairs(valuefound.items) /etc.

Maybe there is a better way of doing this?


Solution

  • if you can change the table then do:

    scavenging = 
    {
     ["Greenskin|16"] = {
        type = "Greenskin|16",
        fast_levelup = 20,        
        normal_levelup = 40,      
        slow_levelup = 40,        
        drops =          
        {
          {items = {"Linen", "Bolt of Linen", "Coarse Thread", "Feather", "Cotton"}, droprates = {60, 10, 10, 10, 2}},
        },
      }, 
    }
    

    and get data directly by index

    print(scavenging["Greenskin|16"].fast_levelup)
    

    otherwise, just by searching as you did.