4
votes

Let's say I have a sequence:

a = { 10, 12, 13 }

The length (#a) of this sequence is 3.

Now, suppose I do the following:

table.insert(a, nil)

(or a[#a+1] = nil.)

Will this affect the table in any way?

Is the answer to this question decisive, or is this "undefined behavior"?

On the Luas I've checked (Lua 5.1, Lua 5.3) this does not affect the table. But I wonder if this is "undefined behavior" on which I cannot rely.

The manual only talks about adding a nil to the middle of a sequence, but it doesn't (according to my interpretation) talk about adding it to the end of the sequence.

2
"Adding a nil to the middle of a sequence" removes the key-value pair from the table. If it was in the middle of the sequence of a table that had a sequence, that table would no longer have a sequence. - Tom Blodget
Even if some hypothetic conforming implementation would "affect" the table instead of just doing nothing, resulting table would still be a sequence by definition. - user3125367
E.g. assignment of nil to last sequence key affects the table, but it is still a sequence afterwards. - user3125367

2 Answers

5
votes

Adding a value of nil to a sequence, has no effect at all. In fact, a table cannot hold a value of nil. From the manual:

Tables can be heterogeneous; that is, they can contain values of all types (except nil). Any key with value nil is not considered part of the table. Conversely, any key that is not part of a table has an associated value nil.

So, a table { 10, 12, 13, nil} is equivalent to { 10, 12, 13 }, both are sequences.

Similarly, a non-sequence example: a table {10, 20, nil, 40} is equivalent to {[1] = 10, [2] = 20, [3] = nil, [4] = 40} or {[1] = 10, [2] = 20, [4] = 40}

2
votes

No it doesn't affect the table.

t = {1,2};
table.insert(t,nil);
table.insert(t,3);
for k,v in ipairs(t) do print(v) end

it returns:

1
2
3