Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Length operator returning 10 instead of 1?

Asked by 5 years ago
Edited 5 years ago

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)
0
thats because you're using the discord bot... theking48989987 2147 — 5y

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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!

0
Let me edit my question so you better understand what I meant by "stops at nil". programmerHere 371 — 5y
0
it doesn't simply stop at nil, hence when it doesn't print your desired number theking48989987 2147 — 5y
0
Well then, maybe a confusion of the length operator and `ipairs`. Thanks! programmerHere 371 — 5y
0
theking u nerd greatneil80 2647 — 5y
Ad

Answer this question