Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua find a key from a value

Tags:

lua

I'm working with this:

chars = {
    ["Nigo Astran"] = "1",
    ["pantera"] = "2"
}
    
nchar = chars[$name] + 1

The variable $name will give me a string that I'm logged in to, in this case: "Nigo Astran" and nchar has the value "2" if I'm in "Nigo Astran", and so on. I believe you get the idea.

Now, I want to get the key from the value, for example:

when nchar is "2" it should give me "pantera" as the key. I'm just not getting the value of the key.

like image 858
Wesker Avatar asked Oct 28 '11 04:10

Wesker


2 Answers

If you find yourself needing to get the key from the value of a table, consider inverting the table as in

function table_invert(t)
   local s={}
   for k,v in pairs(t) do
     s[v]=k
   end
   return s
end
like image 167
lhf Avatar answered Sep 27 '22 22:09

lhf


I don't think there is anything more efficient than looping over the entries in the table using pairs and comparing the keys.

you can do that using something like this

function get_key_for_value( t, value )
  for k,v in pairs(t) do
    if v==value then return k end
  end
  return nil
end

Then you'd use it like this:

local k = get_key_for_value( chars, "1" )
like image 44
Michael Anderson Avatar answered Sep 27 '22 21:09

Michael Anderson