Code: Select all
function isArray(tab)
local countT = 0
local countA = 0
local i = 1
for k,_ in pairs(tab) do
countT = countT + 1
if tab[i] then
countA = countA + 1
end
if countT ~= countA then
return false
end
i = i + 1
end
return true
end
Code: Select all
t = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
t2 = {5,4,8,w=5,6,4,8}
function isArray(tab)
local countT = 0
local countA = 0
local i = 1
for k,_ in pairs(tab) do
countT = countT + 1
if tab[i] then
countA = countA + 1
end
if countT ~= countA then
return false
end
i = i + 1
end
return true
end
local function is_array(t)
local count = 0
for k, _ in pairs(t) do
if type(k) ~= 'number' or k < 1 or math.floor(k) ~= k then return false end
count = count + 1
end
return count == #t
end
print(isArray(t)) --true
print(is_array(t)) --true
print(isArray(t2)) --flase
print(is_array(t2)) --false
t[2] = nil
print(#t) --20
print(isArray(t)) --false
print(is_array(t)) --false
t[20]=nil
t[18]=nil
print(#t) --17?
print(isArray(t)) --false
print(is_array(t)) --true
(tested with lua 5.1, 5.2 JIT 2.0.0,2.0.1,2.0.2 – same thing)