So I was bored and I decided to play around with some things.
I ran these codes:
print(#{1, nil, nil, nil, nil, nil, nil, nil, nil, 10})
From what I know the length operator stops at nil. The first nil value. Since [2]
is nil the length of my array is 1. But it returns 10. Why is this?
Thank you in advance to anyone who answers.
When I said "the length operator stops at nil" this caused the length operator to return three;
print(#{1, 2, 3, nil})
This would print 1:
local arr = {"no"} arr[3] = "yes" print(#arr)
The length operator stops at the last index in an array, not at the first index of nil
, that is ipairs
.
say, for example, i had a table like:
local arr = {1,nil,nil,nil,4}
getting the length of array arr
with the length operator (#
) would return
5
however, if a table was like:
local arr = {1,[10]=45}
getting the length of array arr
with the length operator would return
1
This is due to the way the length operator works. In lua, the length operator returns the last numeric key whose value is not nil for tables starting from 1.
I feel that count guge the cool
did a great job of explaining this on the discord server, but I will be trying to emulate that here:
? is the last element of the array part nil if no ?is the hash part empty if yes return the array size if no return the result of an unbound search if yes return the last non-nil index visited in a binary search
Hopefully this helped!