Lua find a key from a value

前端 未结 3 1974
渐次进展
渐次进展 2020-12-03 19:43

I\'m working with this:

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

   nchar = (chars[$name])+1
<
3条回答
  •  甜味超标
    2020-12-03 20:22

    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" )
    

提交回复
热议问题