4

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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Niccolo M.
  • 3,363
  • 2
  • 22
  • 39
  • "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 Apr 19 '15 at 16:03
  • 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 Apr 20 '15 at 06:03
  • E.g. assignment of nil to *last* sequence key *affects* the table, but it is still a sequence afterwards. – user3125367 Apr 20 '15 at 06:05

2 Answers2

5

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}

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • Just to be clear, the first table in this answer has a sequence. The second table doesn't (that is, it has positive integer keys but they don't meet the definition of both starting at 1 and being contiguous.) – Tom Blodget Apr 19 '15 at 15:55
  • @TomBlodget You are right, I wasn't clear on that. Trying to point out that a `nil` value isn't really in the table is true for any tables, not just sequences. I'm using the second example because I assum OP is referring this when saying *The manual only talks about adding a nil to the middle of a sequence*. I'll edit to make it more clear. – Yu Hao Apr 19 '15 at 16:00
2

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
bizzobaz
  • 95
  • 1
  • 8