Lua 从一个值中找到一个键 [英] Lua find a key from a value

查看:24
本文介绍了Lua 从一个值中找到一个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理这个:

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

变量 $name 会给我一个我登录的字符串,在这种情况下:"Nigo Astran"如果我在 Nigo Astran" 中,nchar 的值为 2",依此类推.我相信你明白了.

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:

nchar"2" 时,它应该给我 "pantera" 作为键.我只是没有得到密钥的值.

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

推荐答案

如果您发现自己需要从表的值中获取键,请考虑将表反转为

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

这篇关于Lua 从一个值中找到一个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆