Why does getting the size of an array break when you do this?

Hi! I found this weird thing where array sizes break if you do this. If you can find anyway to do something like this let me know!

local test = { }
table.insert(test, 1, 'hi')
test['hi'] = nil
print(#test)

whenever I do this the size of the table remains 1… The same works for if I was to add the the value like this
test['hi'] = true

How else could I make this without doing table.remove(test, 1) (mainly cause the positioning is dynamic)

Do you mean how it should be 2 because of 2 indexes with content?

The # operator only accounts for array indexes (numerically from 1 until the last ordered number key), [‘hi’] is not an array index.

Here is a function that can grab the number of contents for any table:

local function count(t)
    local c = 0
    for _ in pairs(t) do
        c += 1
    end
    return c
end
1 Like

You can use table.remove(test,table.find(test,"hi"));
table.find(table,value) returns the index of the value you’re looking for in the specified table.

1 Like