Return first key of the item of table?


(Raul (ulneiz)) #1

The table:

table = { ["name"]="formula1", ["man"] ="formula2" }

How print or return “name” or “man”?

Note : print( table[“name”]) --> “formula1”. How to do the opposite without the need to create a table with the inverted equality?Is there any way?


(joule) #2

Semantically, you’ve stated three different questions. Please clarify. What result do you want?


(Raul (ulneiz)) #3

Semantically, you’ve stated three different questions. Please clarify. What result do you want?

The table:

table = { ["name"]="formula1", ["man"] ="formula2" }

How print"name"?


(danoise) #4

In lua, only tables that use integers as keys have a specific order.

So in you case, there is no guarantee that “name” is the first entry, even if you created it the way you posted.

Only if you settle for e.g. extracting the keys of the table through table.keys(your_table)and then doing a table.sort()on the result will you get a fixed order.


(joule) #5

The table:

table = { ["name"]="formula1", ["man"] ="formula2" }

How print"name"?

OK. I think I’m smart enough to understand that you don’t want me to answer ‘print(“name”)’

tbl = { ["name"]="formula1", ["man"] ="formula2" }

print(table.find(tbl, "formula1"))

Do note that if “formula1” is the value of more than one key, there is no guarantee of which key that will be returned.


(Raul (ulneiz)) #6

OK. I think I’m smart enough to understand that you don’t want me to answer ‘print(“name”)’

^^ ^^ ^_^I took it for granted!

tbl = { ["name"]="formula1", ["man"] ="formula2" }

print(table.find(tbl, "formula1"))

Do note that if “formula1” is the value of more than one key, there is no guarantee of which key that will be returned.

Ok perfect, this will serve me. Yes, the equalities are all different. Thank you very much! :slight_smile: