我如何检查是否一个Lua表只包含连续的数字指标? [英] How can I check if a lua table contains only sequential numeric indices?
问题描述
我怎么能写,确定它是否是表的说法是一个真正的数组?函数
How can I write a function that determines whether it's table argument is a true array?
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
我看不到查不到,如果数字键是唯一键的所有方式。
I can't see any way of finding out if the numeric keys are the only keys.
推荐答案
ipairs迭代指数1..N,其中N + 1是在第一整数索引与零值结果
对遍历所有的键。结果
如果有更多的键比有顺序索引,那么就不能是一个数组。
ipairs iterates over indices 1..n, where n+1 is the first integer index with a nil value
pairs iterates over all keys.
if there are more keys than there are sequential indices, then it cannot be an array.
因此,所有你需要做的就是看是否元素的对数(表)
等于元素的数量 ipairs(表)
结果
的code可以写为如下:
So all you have to do is see if the number of elements in pairs(table)
is equal to the number of elements in ipairs(table)
the code can be written as follows:
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
我是pretty新到Lua,所以可能有一些内建函数以减少numKeys和numIndices计算简单的函数调用。
I'm pretty new to Lua, so there might be some builtin function to reduce the numKeys and numIndices calculations to simple function calls.
这篇关于我如何检查是否一个Lua表只包含连续的数字指标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!