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.
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 valuenil
is not considered part of the table. Conversely, any key that is not part of a table has an associated valuenil
.
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}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With