6

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.

Luke100000
  • 1,395
  • 2
  • 6
  • 18
Wesker
  • 231
  • 1
  • 3
  • 10

3 Answers3

11

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
lhf
  • 70,581
  • 9
  • 108
  • 149
  • well atm im using this code function get_key_for_value( t, value ) for k,v in pairs(t) do if v==value then return k end return nil end now im finding another problem, when my table ends, and returns a nil i want it, to loop from the first value, cant do that yet <, – Wesker Oct 28 '11 at 16:09
  • The for loop is missing a do. – HeMan Aug 31 '13 at 19:04
  • I'd recommend using `ipairs` rather than `pairs`, as it preserves the order of the original table. – Myles Dec 13 '20 at 00:53
3

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" )
Dale K
  • 25,246
  • 15
  • 42
  • 71
Michael Anderson
  • 70,661
  • 7
  • 134
  • 187
  • ok that works but sadly, i cant do like
    nchar = (chars[$name])+1
    
     get_key_for_value( chars, nchar )
    will be nil idk why, that was my problem at the start xD
    – Wesker Oct 28 '11 at 04:39
  • got it i did it with tostring() love you anyways <3 – Wesker Oct 28 '11 at 04:58
0

the best way to do that is like this

 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
Master
  • 19
  • 1