0
a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14

print(#a)

prints 1

a = {}
a[1] = 1
a[2] = nil -- does nothing, as a[2] is already nil
a[3] = 14
a[4] = 5

print(#a)

prints 4

What does the # operator really return?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Łukasz
  • 1,980
  • 6
  • 32
  • 52

1 Answers1

2

If the table is not a proper sequence, the return value of the # operator applied to that table is undefined.

In both of your cases, a is not a proper sequence because a[2] == nil and a[3] ~= nil.

The # operator returns the length of proper sequences.

MarkWeston
  • 740
  • 4
  • 15