返回 Lua 表中某个值的索引 [英] Returning the index of a value in a Lua table

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

问题描述

我在 lua 中有这个表:

I have this table in lua:

local values={"a", "b", "c"}

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

is there a way to return the index of the table if a variable equals one the table entries? say

local onevalue = "a"

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

how can I get the index of "a" or onevalue in the table without iterating all values?

推荐答案

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

The accepted answer works, but there is room for improvement:

  • 一旦找到元素,为什么不退出循环?为什么要把整个源表复制到一个新的一次性表中?
  • 通常,这种函数返回具有该值的第一个数组索引,而不是具有该值的任意数组索引.
  • Why not exit the loop once the element is found? And why bother copying the entire source table into a new throwaway table?
  • Usually, this sort of function returns the first array index with that value, not an arbitrary array index with that value.

对于数组:

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

对于哈希表:

-- 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'

这篇关于返回 Lua 表中某个值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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