How can I get a table's key itself as a string in Lua?

Let’s suppose I have the following table:


foo = {
    ["bar"] = 123,
    ["spam"] = 234
}

I would like to get the key itself as a string, when I say that I mean for example (considering the table above) the key “bar” not its value 123.

There is any way I can do that? Something like keytostring(foo[“bar”]) that would return the string “bar”.



function valToKey( tbl, val )
  for k,v in pairs( tbl ) do
     if v == val then return k end
  end
end

foo = {
    ["bar"] = 123,
    ["spam"] = 234
}

print(valToKey( foo, 123 ))
-- prints bar


Like that?

Could you give an example of where you would use this? If you are going to do foo[“bar”] then you should already know the key? How are you accessing table’s entries?

Ohh god, ignore this this thread, I’m so fucking stupid, you’re right Bo98.

?

Never new that existed haha!