Lua find the key to the value

I am working with this:

    chars = {
         ["Nigo Astran"]="1",
         ["pantera"]="2"
         }

   nchar = (chars[$name])+1

The $ name variable will give me the line that I went into, in this case: "Nigo Astran" and ncharit matters "2"if I'm in "Nigo Astran", etc. I believe that you understand.

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

when nchar 2, he should give me "pantera"as a key. I just don't get the key value.

+5
source share
3 answers

If you need to get the key to the table value, 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
+10
source

I do not think this is more efficient than looping over table elements using pairsand comparing keys.

, -

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

:

local k = get_key_for_value( chars, "1" )
+2

 local autoreply={
['hey']='hi',
['how are u']='am fine what about u?',
['how r u']='am fine what about u?',
['how are you']='am fine what about u?',
['sleep']='rockabye bayby good dreems',
['السلام']='وعليكم السلام ورحمة الله وبركاته',
}
local keys={'hey','how are u','how r u','how are you','sleep','السلام'}
function getValueFromKey(table,key)
  for k,v in ipairs(keys)do
  if string.find(string.upper(key),string.upper(v)) then return table[v] end
  end
   return false
end
0
source

All Articles