Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

roblox - (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)

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...