It happens because table.insert
by default inserts elements at the position #list+1
, but the length operator is only defined for sequences and the table with gaps (as in your case nil, nil, nil, "this works"
or 1, nil, nil, "this works"
or 1, 2, nil, "this works"
) is not a sequence.
You can get a bit more expected result if you use table.insert(t, i, i)
, as this will explicitly specify where the elements need to be inserted (instead of relying on the length operator), but the insertion will still be affected by nil
elements in the table. If you do this, after 4 insertions you may get {1, 2, 3, 4, "this works"}
and after 5 insertions you may get {1, 2, 3, 4, 5, "this works"}
, which may or may not be what you need.
(To specifically answer your question about multiples of 4: the length operator is using binary search, which also depends on the number of elements already stored in the array part of the table. When you have 1, 2, nil, 4
, the algorithms finds 2 and then finds 4, which satisfies the criterion for the length value for sequences (n
value is not nil
, but n+1
value is), so it returns 4 and the next element is inserted at the position 5 and not 3 as you'd probably expect.)