Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Length operator returning 10 instead of 1?

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.


Edit

When I said "the length operator stops at nil" this caused the length operator to return three;

print(#{1, 2, 3, nil})

Edit2

This would print 1:

local arr = {"no"}
arr[3] = "yes"
print(#arr)

1 comment

0

thats because you're using the discord bot...

1 answer

✓ Accepted answer

Length Operator


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.


Addition


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!

4 comments

0

Let me edit my question so you better understand what I meant by "stops at nil".

0

it doesn't simply stop at nil, hence when it doesn't print your desired number

0

Well then, maybe a confusion of the length operator and ipairs. Thanks!

0

theking u nerd

This discussion is preserved as it was. New answers, comments, and votes are closed.