Search code examples
luanestedlua-table

How best can I find the key of a specific value in a nested situation?


In a Lua table, how best can I find the key of a specific value in a nested situation (following table, originating from JSON)?

[{"Code": "AF", "Name": "Afghanistan"},
{"Code": "AL", "Name": "Albania"},
...
]

For example, I can use table[2]["Name"] to fetch "Albania", but how can I get [2], only by specifying "Albania"?


Solution

  • Loop over the array and test each value:

    for i,v in ipairs(table) do
        if v.Name == "Albania" then
            return v.Code
        end
    end
    

    You can also put the values as key-pair in a new table once so you can query directly:

    local codeFromName={}
    for i,v in ipairs(table) do
        codeFromName[v.Name]=v.Code
    end