Search code examples
luaroblox

(LUA) Is there a function or method to get the KEY from a table


    {
    ["Question"] = "A stupid one";
    }

What is the best way to get the first key of a table?

I was thinking I could iterate through the loop, but surely there is a better method, or built-in function.

Thanks!

(This is my first time using StackOverflow so I apologise if I did anything wrong)


Solution

  • You still have to iterate to get key.

    You can use pairs for any keys and ipairs for sequential integer keys starting from 1.

    pairs uses next function which returns next key in the table but it can't be used to find specific key without iterating it.

    To find a key for the value "A stupid one" use this:

    for k,v in pairs(t) do
        if v == "A stupid one" then
           print("Key is:", k)
           break
        end
    end