Search code examples
luakeylua-table

Get table key name from value


I'm trying to get table key name from a value. tostring only returns table: XXXXXXXXX

I tried some functions but nothing work.

config = {
    opt1 = "etc..."
}
players = {}

function openMenu(playerName, configTable)
    players[playerName] = Something to get Table Key...

    -- read the table and create a gui not yet made
end

And next, if I do this :

print(players[playerName])

I want to get this output :

"config"

Solution

  • You will need to iterate over all pairs of the table and return the key if the value is equal. Note that this will only return one binding, even if multiple keys can lead to the same value:

    function find(tbl, val)
        for k, v in pairs(tbl) do
            if v == val then return k end
        end
        return nil
    end