How to get the length of a Lua array 

Joined:
04/07/2009
Posts:
178

April 15, 2014 16:20:36    Last update: April 15, 2014 16:20:36
For arrays with numerical indices:
> a = { 'a', 'b' }
> =#a
2
> =table.getn(a)
2
> for i, v in ipairs(a) do
>> print('i: '.. i .. ', v: ' .. v)
>> end
i: 1, v: a
i: 2, v: b
> 


However, the # operator or table.getn does not count elements with string indices:
> a['a'] = 1
> a['b'] = 2
> return #a
2
> =table.getn(a)
2
> for i, v in ipairs(a) do
print('i: '.. i .. ', v: ' .. v)
end
i: 1, v: a
i: 2, v: b
> for i, v in pairs(a) do
print('i: '.. i .. ', v: ' .. v)
end
i: 1, v: a
i: 2, v: b
i: a, v: 1
i: b, v: 2
> 


Further, the pairs function does not list keys accessible made available via setmetatable:
> setmetatable(a, {__index = function(table, key) 
>> if key == 'c' then
>> return 3
>> end
>> end })
> =a.c
3
> for i, v in pairs(a) do
print('i: '.. i .. ', v: ' .. v)
end
i: 1, v: a
i: 2, v: b
i: a, v: 1
i: b, v: 2



Share |
| Comment  | Tags