-1

I was messing around with Lua tables and I noticed:

local t1 = {1, 5, nil, 10}
local t2 = {1, 5, nil, 10, nil}

print(t1[5], t2[5]) --> nil   nil
print(#t1, #t2) --> 4   2

I was expecting the length of both tables to be 4, but the length of t2 turned out to be 2. Can anyone explain this?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
David
  • 693
  • 1
  • 7
  • 20
  • It's just easier to call `#` the _sequence length operator_ and `ipairs` the _sequence iterator._ Neither of your tables have a sequence. (It seems to be an unstated requirement that `#` return a non-negative integer even when invoked on a table without a sequence.) All of these behaviors enable time and space optimizations for sequences. – Tom Blodget Apr 21 '15 at 16:59

1 Answers1

2

Frequently, in Lua, we assume that an array ends just before its first nil element. This convention has one drawback: We cannot have a nil inside an array. [...] But sometimes we must allow nils inside an array. In such cases, we need a method to keep an explicit size for an array.

From Programming in Lua 19.1.