我试图在 Garry's mod Lua 中找到与表的值关联的键,但我收到错误,就好像它不是表一样。
这是我正在维护/修复的其他人代码上的游戏崩溃错误的更大解决方案的一部分。
长话短说,我需要根据密钥的值来获取密钥的编号。一个存在此问题的简单、简短的代码:
function starttest()
local tbl = {"a", "b", "c"}
local printme = FindValueInTable(tbl, "c")
print(printme)
end
function FindValueInTable(table, value)
for k, v in table do --errors on this line saying "attempt to call a table value"
if v == value then
return k
end
end
return nil
end
Run Code Online (Sandbox Code Playgroud)
我不知道在这里要做什么,因为它table实际上是一张桌子,怎么可能for k,v in table真的失败呢?
我期望的结果是它返回具有 中值的数字键value。因此,如果value == "c"和table[3]恰好有该值,"c"那么它应该3作为结果返回。