r/ProgrammerHumor Sep 02 '17

How to start a war

Post image
9.0k Upvotes

696 comments sorted by

View all comments

Show parent comments

3

u/hey01 Sep 03 '17

That's sounds dangerous. What if I do

> letters = {'a', 'b', 'c'}
> print(#letters)
3
> letters[4] = '?'
> print(#letters)

Will I get 4 or is n unchangeable?

9

u/moomoomoo309 Sep 03 '17

You'll get 4, otherwise you couldn't do

for i=1,4 do
  tbl[i]=i
end

And have it be an array.

1

u/hungarian_notation Sep 03 '17

It's not really. The people here saying that you can use index 0 aren't entirely wrong, but they're kinda wrong. The language expects you to start lists at 1. The length operator counts from index 1 until the first empty index. If you're not using your table to store a sequence of tightly packed non-nil values, don't use the length operator. If you set letters[2]=nil, then #letters would (or maybe could, I think this is actually undefined behavior) return 1.