Some less bureaucratic way to obtain a dictionary key?

I have this dictionary (it will have more keys in other parts of the program, but in this part, there is only one key):

d = {keyA = 1}

I want to get only the first key name (not the value).

So I have to do this:

local firstKey
for k, _ in pairs(d) do
    firstKey = k
    break
end
print(firstKey)

… 6 lines to get a single key.
Is there a more direct way to get this key?

You could use:

local firstKey = next( d )

Please note that the order you get when you have multiple entries may not be what you expect.
Edit: typo

1 Like

Interesting thing: if I simply print the next I get the key + value as a string (as stated here: “It returns the next index of the table and the value associated with the index”

local d = {keyA = 23}
print(next(d))

will print

keyA 23

But if I put the next in a variable, it stores only the key name (not the value):

local v = next(d)
print(v)

prints only:

keyA

Why?

Yes, next() returns multiple values, and print() can print multiple values, eg:

local a, b = 5, 6
print( a, b )
1 Like

… and a = 5, 6 will store only the first value (5).
That’s why.
Thank you!

That is correct…

Not exactly related, but a bit of a fun fact I guess. pairs actually returns next, so calling it would allow you to do something like this instead:

local key = pairs{}(table)

There’s no reason to do this, but it’s interesting to know how it’s implemented in my opinion.

3 Likes

Now a question about using next in dictionaries:

local d = {keyA = 23, keyB = 24, keyC = 25}
print(next(d)) 
print(next(d))
print(next(d))

will always print:

KeyB 2
KeyB 2
KeyB 2

Why? I think the terms “next” might be to get the “next” item, not always the same…

Feed in the previous key from next() as the 2nd argument to next()

2 Likes

… and then realize with horror that you’ve re-implemented pairs :slight_smile:

1 Like