如何检查lua表是否只包含连续数字索引?

Eri*_*ric 7 arrays lua dictionary lua-table

如何编写一个函数来确定它的表参数是否为真数组?

isArray({1, 2, 4, 8, 16}) -> true
isArray({1, "two", 3, 4, 5}) -> true
isArray({1, [3]="two", [2]=3, 4, 5}) -> true
isArray({1, dictionaryKey = "not an array", 3, 4, 5}) -> false
Run Code Online (Sandbox Code Playgroud)

我看不出有什么方法可以找出数字键是否是唯一的键.

kik*_*ito 16

编辑:这是我最近发现的一种测试阵列的新方法.对于返回的每个元素pairs,它只是检查其上的第n个项目不是nil.据我所知,这是测试阵列的最快,最优雅的方法.

local function isArray(t)
  local i = 0
  for _ in pairs(t) do
    i = i + 1
    if t[i] == nil then return false end
  end
  return true
end
Run Code Online (Sandbox Code Playgroud)

  • 优化:删除`isSequential`.相反,如果正整数键的数量是"n",那么你可以"返回n == max" (2认同)

Pon*_*dle 4

ipairs 迭代索引 1..n,其中 n+1 是第一个具有 nil 值对的整数索引,
迭代所有键。
如果键的数量多于顺序索引的数量,则它不能是数组。

所以你要做的就是看看里面的元素个数是否pairs(table)等于ipairs(table)
代码中的元素个数可以写成如下:

function isArray(tbl)
    local numKeys = 0
    for _, _ in pairs(tbl) do
        numKeys = numKeys+1
    end
    local numIndices = 0
    for _, _ in ipairs(tbl) do
        numIndices = numIndices+1
    end
    return numKeys == numIndices
end
Run Code Online (Sandbox Code Playgroud)

我对 Lua 还很陌生,所以可能有一些内置函数可以将 numKeys 和 numIndices 计算减少为简单的函数调用。