Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

    {
    ["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)

question from:https://stackoverflow.com/questions/65890119/lua-is-there-a-function-or-method-to-get-the-key-from-a-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
777 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...