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?
Club_Moo
(Club_Moo)
July 21, 2020, 3:09pm
#2
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?
Club_Moo
(Club_Moo)
July 21, 2020, 3:50pm
#4
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!
posatta
(pasta)
July 21, 2020, 4:03pm
#7
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…
Club_Moo
(Club_Moo)
July 21, 2020, 5:58pm
#9
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
1 Like