Why are tables like this?

I was scripting and I was having problems, I started to print certain things to figure out what the problem was and I noticed that getting the number of things on a table wasn’t actually working the way I thought.

local t = {}
t[1] = 4
t[4] = 4
t[3] = 4

print(#t) -- Outputs: 4

local z = {}
z[1] = 4
z[4] = 4

print(#z) -- Outputs: 1
1 Like

Adding to what @fellow_meerkat said, fact that print(#t) outputs 4 instead of 2 is actually a bug! Or, at the very least, a form of undefined behavior due to some aggressive optimization regarding array-like Tables.

The # operator for getting the “length” of a Table is only valid if the Table’s array portion does not contain any holes: indices where the value is nil in between indices that contain data.

Notably, it does not work for dictionary-like Tables in any form. For that, you need to either keep track of it as you insert or remove elements, or write a custom “counter” function as @fellow_meerkat suggested.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.