返回Lua表中值的索引

Ami*_*mir 3 lua lua-table

我在lua中有这个表:

local values={"a", "b", "c"}
Run Code Online (Sandbox Code Playgroud)

如果变量等于表条目中的一个,有没有办法返回表的索引?说

local onevalue = "a"
Run Code Online (Sandbox Code Playgroud)

如何在不迭代所有值的情况下获取表中"a"或onevalue的索引?

lhf*_*lhf 9

没有迭代就没有办法做到这一点.

如果您发现自己需要经常这样做,请考虑构建反向索引:

local index={}
for k,v in pairs(values) do
   index[v]=k
end
return index["a"]
Run Code Online (Sandbox Code Playgroud)


Mar*_*ese 7

接受的答案有效,但还有改进的空间:

  • 为什么找到元素后不退出循环?为什么还要将整个源表复制到新的一次性表中呢?
  • 通常,此类函数返回具有该值的第一个数组索引,而不是具有该值的任意数组索引。

对于数组:

-- Return the first index with the given value (or nil if not found).
function indexOf(array, value)
    for i, v in ipairs(array) do
        if v == value then
            return i
        end
    end
    return nil
end

print(indexOf({'b', 'a', 'a'}, 'a'))  -- 2
Run Code Online (Sandbox Code Playgroud)

对于哈希表:

-- Return a key with the given value (or nil if not found).  If there are
-- multiple keys with that value, the particular key returned is arbitrary.
function keyOf(tbl, value)
    for k, v in pairs(tbl) do
        if v == value then
            return k
        end
    end
    return nil
end

print(keyOf({ a = 1, b = 2 }, 2))  -- 'b'
Run Code Online (Sandbox Code Playgroud)