lualua-table

Getting the key a value was assigned to in a table in lua


So I'm trying to make a table of all the creatures in a game, each creature consisting of a table with their stats. I used the creature's name as the key in the first table, but now I need to get that name, but I'm not sure how/if you can do that?

local creatureArray = {["White Wyrm"]= {
    ["dungeon"]= "Cavernam",
    ["slayer"]= "Beastial",
    ["difficulty"]= 100.8,
    ["goldvalue"]= 1008,
    ["hits"]= 4500,
    ["mindmg"]= 45,
    ["maxdmg"]= 55,
    ["wrestling"]= 105,
    ["armor"]= 50,
    ["magicresist"]= 25,
    ["ai"]= "Melee",
    ["speed"]= "Medium",
    ["uniquescaler"]= 1.35
},
}

In the example above when I iterate over this entry in the "creatureArray" I need to get the "White Wyrm" value, or the key that the sub-table is assigned to? I feel like the answer must be really simple, but I've found it hard to find answers because I'm referring to tables inside tables and probably using the wrong terminology to begin with.

For those who were wondering the game is Ultima Online Outlands, I have no affiliation with them, I'm just working on a Lua module to hopefully integrate into their community-run wiki.

I tried just referencing the table since I'm using a for loop to iterate over all of the creatures: for i, creature in pairs(creatureArray) In this example I tried just using "creature", but that references the table object itself and not the key.

I'm know I could add a value under each creature called "name", but that just seems redundant.


Solution

  • for i, creature in pairs(creatureArray)
    

    When looping through a table or dictionary, it returns a key/value pair. The i is considered the key, and the creature is considered the value.

    Here's an example:

    local t = {
        ["Item"] = "Value",
        ["Another Item"] = "Another Value",
    }
    
    for i, value in pairs(t) do
        print(i, value)
    end
    

    The output would be:

    Item            Value
    Another Item    Another Value