Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending nil to a Lua sequence

Tags:

lua

lua-table

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.

like image 922
Niccolo M. Avatar asked Mar 16 '23 09:03

Niccolo M.


2 Answers

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}

like image 96
Yu Hao Avatar answered Apr 28 '23 20:04

Yu Hao


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
like image 39
bizzobaz Avatar answered Apr 28 '23 20:04

bizzobaz