Table/array bug?

So I was experimenting on a table for my gear system and I found this bug like when there’s an undefined variable in an array Like this

local myTable = {
	[1] = 1,
	[2] = 2,
	[4] = "lol"
}
table.insert(myTable,3)
print(myTable)
print(#myTable)

You might think that the 3 value will have an index of 3 and the length of the table is 4 but its not
image
It gave me an index of 5 on value 3 and a length of 5 but wait the 3 index seems to have a value called void what is that?

Now lets make 2 undefined variables

local myTable = {
	[1] = 1,
	[2] = 2,
	[5] = "lol"
}

image
now look the index of the value 3 is now 3 but wait it just gave me 3 as length of the array but its clearly 4 as you can see
anyone knows why is this happening?

2 Likes

It’s not a bug, but rather that the behavior of the # operator on sparse arrays is undefined and you should not rely on it. You can instead construct your tables using table.pack and read the n field to get the length instead if you really need this.

print(#{ nil, nil, nil }) --> 0
print(table.pack(nil, nil, nil).n) --> 3
4 Likes

have another question the thing is i need it to be sequential that’s why im using table.insert to fill up the undefined variable but its not working.

I also dont need to count the nil values

1 Like

If you know the index you can do myTable[3] = 3 or something, you can’t rely on sparse arrays at all.

2 Likes