Sparse array in Lua?

Not an SDK question, a Lua syntax one.

I need a sparse array, however, when I use a table the count (#foo) is only counting the non-sparse sub-array from 1.

local foo = {}
printTable(foo)
print("count:", #foo)
table.insert(foo, 1, "One")
foo[2] = "Two"
printTable(foo)
print("count:", #foo)
foo[3] = "Three"
printTable(foo)
print("count:", #foo)
foo[5] = "Five"
printTable(foo)
print("count:", #foo)
foo[4] = nil
printTable(foo)
print("count:", #foo)

Output:

{
}
count:	0
{
	One,
	Two,
}
count:	2
{
	One,
	Two,
	Three,
}
count:	3
{
	One,
	Two,
	Three,
	Five,
}
count:	3
{
	One,
	Two,
	Three,
	Five,
}
count:	3

How can I implement a sparse array that I can add to at arbitrary indexes?

OK. Just figured it out. You can iterate through all the elements with pairs (nil is not returned)

for index, value in pairs(foo) do
    print("i:", index, "v", value)
end
i:  1   v   One
i:  2   v   Two
i:  3   v   Three
i:  5   v   Five
3 Likes